Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

307
Views
Firebase firestore is there a way to write data from an array into a document and then subcollections?

I'm new to firebase in general and am trying to write parts of an array into a document and its remaining data in a document in a subcollection. Here is what I've done:

let db = admin.firestore();    
db.collection("User")
          .doc(fields.user)
          .collection("Address")
          .doc(fields.address)
          .set({
            User: fields.user,
            Address: fields.address,
          })
          .then(
            db.collection("User")
              .doc(fields.user)
              .collection("Address")
              .doc(fields.address)
              .collection("Orders")
              .doc(fields.ID)
              .set({
                ID: fields.ID,
              });

My biggest question is if there is a better way to do this? Here its a small sample but for cases it can get very long. Thanks in advance for any help.

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

if you have all the data in the first time. you can create your object with subcollections and then set it in one request

var obj = {
        User: fields.user,
        Address: fields.address,
        Orders: {
          ID: fields.ID,
        }
}
db.collection("User").doc(fields.user).set(obj)
.then(() => {
    console.log("Document successfully written!");
})
.catch((error) => {
    console.error("Error writing document: ", error);
});
about 4 years ago · Santiago Gelvez Report

0

I often prefer constructing longer paths using string interpolation, which would lead to:

db.doc(`User/${fields.user}/Address/${fields.address}`)
  .set({
    User: fields.user,
    Address: fields.address,
  })
  .then(
    db.doc(`User/${fields.user}/Address/${fields.address}/Orders/${fields.ID}`)
      .set({
        ID: fields.ID,
      });

Aside from that, you probably want to do this in a batched write so that either both of the writes succeed, or neither of them does.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!