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;








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: []










share|improve this question
































    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: []










    share|improve this question




























      0












      0








      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: []










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      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

























          1 Answer
          1






          active

          oldest

          votes


















          1















          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.






          share|improve this answer



























          • 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











          • 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










          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
          );



          );













          draft saved

          draft discarded


















          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









          1















          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.






          share|improve this answer



























          • 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











          • 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















          1















          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.






          share|improve this answer



























          • 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











          • 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













          1














          1










          1









          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.






          share|improve this answer















          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          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 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











          • 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












          • 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











          • 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








          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.



















          draft saved

          draft discarded
















































          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.




          draft saved


          draft discarded














          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





















































          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







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해