Firestore how to add to a sub collectionHow do JavaScript closures work?Add table row in jQueryHow do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?How do I return the response from an asynchronous call?
Where should I draw the line on follow up questions from previous employer
Answer with an image of my favorite musician
Pen test results for web application include a file from a forbidden directory that is not even used or referenced
Inspiration for failed idea?
Is Nikon D500 a good fit for nature and ambient-lighting portraits and occasional other uses?
How to differentiate between two people with the same name in a story?
Necessity of tenure for lifetime academic research
Cauterizing a wound with metal?
Can I lend a small amount of my own money to a bank at the federal funds rate?
Did ancient peoples ever hide their treasure behind puzzles?
Scaling arrows.meta with tranform shape
In Endgame, wouldn't Stark have remembered Hulk busting out of the stairwell?
Why are JWST optics not enclosed like HST?
What checks exist against overuse of presidential pardons in the USA?
Why do IR remotes influence AM radios?
I feel cheated on by my new employer, does this sound right?
How can I fix cracks between the bathtub and the wall surround?
How do Barton (Hawkeye/Ronin) and Romanov (Black Widow) end up on the Benatar on Morag in 2014?
Why did the population of Bhutan drop by 70% between 2007 and 2008?
Why does the weaker C–H bond have a higher wavenumber than the C=O bond?
Heat output from a 200W electric radiator?
What is the sound/audio equivalent of "unsightly"?
What is the difference between ?int $number and int $number = null?
How can I throw a body?
Firestore how to add to a sub collection
How do JavaScript closures work?Add table row in jQueryHow do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I include a JavaScript file in another JavaScript file?How to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?How do I return the response from an asynchronous call?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I would like to find a doc in a collection, and add items to a sub collection (which might not exist yet):
projects (collection)
project (doc)
cluster (collection) // might not exist
node1 (doc) // might not exist
statTypeA (collection) // might not exist
I was hoping for something like this:
// Know the doc:
db.ref(`projects/$projectId/cluster/node1/$statType`).add()
// Or filter and ref:
db.collection('projects').where(..).limit(1).ref(`cluster/node1/$statType`).add()
I ended up solving it like this but it's ugly, verbose and slow as it has to come back with a number of read ops first. Am I doing this right?
const projectRefs = await db.collection('projects')
.where('licenseKey', '==', licenseKey)
.limit(1)
.get();
if (!projectRefs.docs)
// handle 404
const projectRef = projectRefs.docs[0].ref;
const cluster = await projectRef.collection('cluster')
.doc('node1').get();
await cluster.ref.collection(statType).add( something: 'hi' );
Edit:
The way I ended up handling this in a better way is a combination of flattening to other collections and also using arrays for stats. Feels much better:
// projects
projectId1
// instances (to-many-relationship) (filter based on projectId)
projectId
statTypeA: []
statTypeB: []
javascript firebase google-cloud-firestore
add a comment |
I would like to find a doc in a collection, and add items to a sub collection (which might not exist yet):
projects (collection)
project (doc)
cluster (collection) // might not exist
node1 (doc) // might not exist
statTypeA (collection) // might not exist
I was hoping for something like this:
// Know the doc:
db.ref(`projects/$projectId/cluster/node1/$statType`).add()
// Or filter and ref:
db.collection('projects').where(..).limit(1).ref(`cluster/node1/$statType`).add()
I ended up solving it like this but it's ugly, verbose and slow as it has to come back with a number of read ops first. Am I doing this right?
const projectRefs = await db.collection('projects')
.where('licenseKey', '==', licenseKey)
.limit(1)
.get();
if (!projectRefs.docs)
// handle 404
const projectRef = projectRefs.docs[0].ref;
const cluster = await projectRef.collection('cluster')
.doc('node1').get();
await cluster.ref.collection(statType).add( something: 'hi' );
Edit:
The way I ended up handling this in a better way is a combination of flattening to other collections and also using arrays for stats. Feels much better:
// projects
projectId1
// instances (to-many-relationship) (filter based on projectId)
projectId
statTypeA: []
statTypeB: []
javascript firebase google-cloud-firestore
add a comment |
I would like to find a doc in a collection, and add items to a sub collection (which might not exist yet):
projects (collection)
project (doc)
cluster (collection) // might not exist
node1 (doc) // might not exist
statTypeA (collection) // might not exist
I was hoping for something like this:
// Know the doc:
db.ref(`projects/$projectId/cluster/node1/$statType`).add()
// Or filter and ref:
db.collection('projects').where(..).limit(1).ref(`cluster/node1/$statType`).add()
I ended up solving it like this but it's ugly, verbose and slow as it has to come back with a number of read ops first. Am I doing this right?
const projectRefs = await db.collection('projects')
.where('licenseKey', '==', licenseKey)
.limit(1)
.get();
if (!projectRefs.docs)
// handle 404
const projectRef = projectRefs.docs[0].ref;
const cluster = await projectRef.collection('cluster')
.doc('node1').get();
await cluster.ref.collection(statType).add( something: 'hi' );
Edit:
The way I ended up handling this in a better way is a combination of flattening to other collections and also using arrays for stats. Feels much better:
// projects
projectId1
// instances (to-many-relationship) (filter based on projectId)
projectId
statTypeA: []
statTypeB: []
javascript firebase google-cloud-firestore
I would like to find a doc in a collection, and add items to a sub collection (which might not exist yet):
projects (collection)
project (doc)
cluster (collection) // might not exist
node1 (doc) // might not exist
statTypeA (collection) // might not exist
I was hoping for something like this:
// Know the doc:
db.ref(`projects/$projectId/cluster/node1/$statType`).add()
// Or filter and ref:
db.collection('projects').where(..).limit(1).ref(`cluster/node1/$statType`).add()
I ended up solving it like this but it's ugly, verbose and slow as it has to come back with a number of read ops first. Am I doing this right?
const projectRefs = await db.collection('projects')
.where('licenseKey', '==', licenseKey)
.limit(1)
.get();
if (!projectRefs.docs)
// handle 404
const projectRef = projectRefs.docs[0].ref;
const cluster = await projectRef.collection('cluster')
.doc('node1').get();
await cluster.ref.collection(statType).add( something: 'hi' );
Edit:
The way I ended up handling this in a better way is a combination of flattening to other collections and also using arrays for stats. Feels much better:
// projects
projectId1
// instances (to-many-relationship) (filter based on projectId)
projectId
statTypeA: []
statTypeB: []
javascript firebase google-cloud-firestore
javascript firebase google-cloud-firestore
edited Apr 4 at 15:20
Dominic
asked Mar 27 at 21:59
DominicDominic
32k10 gold badges78 silver badges95 bronze badges
32k10 gold badges78 silver badges95 bronze badges
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Your "nasty thing" is much closer to the way things work.
In your first attempt, you're trying to combine a query and a document creation in one operation. The SDK doesn't work like that at all. You are either reading or writing with any given bit of code, never both at once. You should do the query first, find the document, then use that to create more documents.
get() returns a promise that you need to use to wait on the results of the query. The results are not available immediately, as your code is currently assuming.
The documentation shows example code of how to handle the results of an asynchronous query. Since your code uses async/await, you can convert it as needed. Note that you have to iterate the QuerySnapshot obtained from the returned promise to see if a document is found.
Hm strange as I am callingawaiton theget(), I think I must be doing the next bit wrong. I might end up just using arrays due to it causing an increase in read/write ops and more complication in code and time to wait for round trips for the benefit of scaling when collections are very large (unlikely in many cases)
– Dominic
Mar 28 at 9:13
YourprojectRefisn't a reference at all. It's a DocumentSnapshot that contains the data in the document. Maybe you want to get a DocumentReference from that snapshot using its ref property and use that to build the next reference. firebase.google.com/docs/reference/js/…
– Doug Stevenson
Mar 28 at 15:11
Thanks I think that might be what I need - will try later
– Dominic
Mar 28 at 15:16
I got it working using ref but it seems like such a poor API I'm still wondering if I'm doing it right (see edited question)
– Dominic
Mar 28 at 18:45
Sure, you're doing it right.
– Doug Stevenson
Mar 28 at 18:58
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387124%2ffirestore-how-to-add-to-a-sub-collection%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your "nasty thing" is much closer to the way things work.
In your first attempt, you're trying to combine a query and a document creation in one operation. The SDK doesn't work like that at all. You are either reading or writing with any given bit of code, never both at once. You should do the query first, find the document, then use that to create more documents.
get() returns a promise that you need to use to wait on the results of the query. The results are not available immediately, as your code is currently assuming.
The documentation shows example code of how to handle the results of an asynchronous query. Since your code uses async/await, you can convert it as needed. Note that you have to iterate the QuerySnapshot obtained from the returned promise to see if a document is found.
Hm strange as I am callingawaiton theget(), I think I must be doing the next bit wrong. I might end up just using arrays due to it causing an increase in read/write ops and more complication in code and time to wait for round trips for the benefit of scaling when collections are very large (unlikely in many cases)
– Dominic
Mar 28 at 9:13
YourprojectRefisn't a reference at all. It's a DocumentSnapshot that contains the data in the document. Maybe you want to get a DocumentReference from that snapshot using its ref property and use that to build the next reference. firebase.google.com/docs/reference/js/…
– Doug Stevenson
Mar 28 at 15:11
Thanks I think that might be what I need - will try later
– Dominic
Mar 28 at 15:16
I got it working using ref but it seems like such a poor API I'm still wondering if I'm doing it right (see edited question)
– Dominic
Mar 28 at 18:45
Sure, you're doing it right.
– Doug Stevenson
Mar 28 at 18:58
add a comment |
Your "nasty thing" is much closer to the way things work.
In your first attempt, you're trying to combine a query and a document creation in one operation. The SDK doesn't work like that at all. You are either reading or writing with any given bit of code, never both at once. You should do the query first, find the document, then use that to create more documents.
get() returns a promise that you need to use to wait on the results of the query. The results are not available immediately, as your code is currently assuming.
The documentation shows example code of how to handle the results of an asynchronous query. Since your code uses async/await, you can convert it as needed. Note that you have to iterate the QuerySnapshot obtained from the returned promise to see if a document is found.
Hm strange as I am callingawaiton theget(), I think I must be doing the next bit wrong. I might end up just using arrays due to it causing an increase in read/write ops and more complication in code and time to wait for round trips for the benefit of scaling when collections are very large (unlikely in many cases)
– Dominic
Mar 28 at 9:13
YourprojectRefisn't a reference at all. It's a DocumentSnapshot that contains the data in the document. Maybe you want to get a DocumentReference from that snapshot using its ref property and use that to build the next reference. firebase.google.com/docs/reference/js/…
– Doug Stevenson
Mar 28 at 15:11
Thanks I think that might be what I need - will try later
– Dominic
Mar 28 at 15:16
I got it working using ref but it seems like such a poor API I'm still wondering if I'm doing it right (see edited question)
– Dominic
Mar 28 at 18:45
Sure, you're doing it right.
– Doug Stevenson
Mar 28 at 18:58
add a comment |
Your "nasty thing" is much closer to the way things work.
In your first attempt, you're trying to combine a query and a document creation in one operation. The SDK doesn't work like that at all. You are either reading or writing with any given bit of code, never both at once. You should do the query first, find the document, then use that to create more documents.
get() returns a promise that you need to use to wait on the results of the query. The results are not available immediately, as your code is currently assuming.
The documentation shows example code of how to handle the results of an asynchronous query. Since your code uses async/await, you can convert it as needed. Note that you have to iterate the QuerySnapshot obtained from the returned promise to see if a document is found.
Your "nasty thing" is much closer to the way things work.
In your first attempt, you're trying to combine a query and a document creation in one operation. The SDK doesn't work like that at all. You are either reading or writing with any given bit of code, never both at once. You should do the query first, find the document, then use that to create more documents.
get() returns a promise that you need to use to wait on the results of the query. The results are not available immediately, as your code is currently assuming.
The documentation shows example code of how to handle the results of an asynchronous query. Since your code uses async/await, you can convert it as needed. Note that you have to iterate the QuerySnapshot obtained from the returned promise to see if a document is found.
edited Mar 28 at 10:28
Alex Mamo
56.1k11 gold badges40 silver badges75 bronze badges
56.1k11 gold badges40 silver badges75 bronze badges
answered Mar 27 at 22:16
Doug StevensonDoug Stevenson
107k12 gold badges124 silver badges149 bronze badges
107k12 gold badges124 silver badges149 bronze badges
Hm strange as I am callingawaiton theget(), I think I must be doing the next bit wrong. I might end up just using arrays due to it causing an increase in read/write ops and more complication in code and time to wait for round trips for the benefit of scaling when collections are very large (unlikely in many cases)
– Dominic
Mar 28 at 9:13
YourprojectRefisn't a reference at all. It's a DocumentSnapshot that contains the data in the document. Maybe you want to get a DocumentReference from that snapshot using its ref property and use that to build the next reference. firebase.google.com/docs/reference/js/…
– Doug Stevenson
Mar 28 at 15:11
Thanks I think that might be what I need - will try later
– Dominic
Mar 28 at 15:16
I got it working using ref but it seems like such a poor API I'm still wondering if I'm doing it right (see edited question)
– Dominic
Mar 28 at 18:45
Sure, you're doing it right.
– Doug Stevenson
Mar 28 at 18:58
add a comment |
Hm strange as I am callingawaiton theget(), I think I must be doing the next bit wrong. I might end up just using arrays due to it causing an increase in read/write ops and more complication in code and time to wait for round trips for the benefit of scaling when collections are very large (unlikely in many cases)
– Dominic
Mar 28 at 9:13
YourprojectRefisn't a reference at all. It's a DocumentSnapshot that contains the data in the document. Maybe you want to get a DocumentReference from that snapshot using its ref property and use that to build the next reference. firebase.google.com/docs/reference/js/…
– Doug Stevenson
Mar 28 at 15:11
Thanks I think that might be what I need - will try later
– Dominic
Mar 28 at 15:16
I got it working using ref but it seems like such a poor API I'm still wondering if I'm doing it right (see edited question)
– Dominic
Mar 28 at 18:45
Sure, you're doing it right.
– Doug Stevenson
Mar 28 at 18:58
Hm strange as I am calling
await on the get(), I think I must be doing the next bit wrong. I might end up just using arrays due to it causing an increase in read/write ops and more complication in code and time to wait for round trips for the benefit of scaling when collections are very large (unlikely in many cases)– Dominic
Mar 28 at 9:13
Hm strange as I am calling
await on the get(), I think I must be doing the next bit wrong. I might end up just using arrays due to it causing an increase in read/write ops and more complication in code and time to wait for round trips for the benefit of scaling when collections are very large (unlikely in many cases)– Dominic
Mar 28 at 9:13
Your
projectRef isn't a reference at all. It's a DocumentSnapshot that contains the data in the document. Maybe you want to get a DocumentReference from that snapshot using its ref property and use that to build the next reference. firebase.google.com/docs/reference/js/…– Doug Stevenson
Mar 28 at 15:11
Your
projectRef isn't a reference at all. It's a DocumentSnapshot that contains the data in the document. Maybe you want to get a DocumentReference from that snapshot using its ref property and use that to build the next reference. firebase.google.com/docs/reference/js/…– Doug Stevenson
Mar 28 at 15:11
Thanks I think that might be what I need - will try later
– Dominic
Mar 28 at 15:16
Thanks I think that might be what I need - will try later
– Dominic
Mar 28 at 15:16
I got it working using ref but it seems like such a poor API I'm still wondering if I'm doing it right (see edited question)
– Dominic
Mar 28 at 18:45
I got it working using ref but it seems like such a poor API I'm still wondering if I'm doing it right (see edited question)
– Dominic
Mar 28 at 18:45
Sure, you're doing it right.
– Doug Stevenson
Mar 28 at 18:58
Sure, you're doing it right.
– Doug Stevenson
Mar 28 at 18:58
add a comment |
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55387124%2ffirestore-how-to-add-to-a-sub-collection%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown