-2

I got this function to add data to a Firestore db and was wondering how to do it in the newer version.

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

This function is to add a document with data in a collection then create a subcollection with a diferent document with its own data. The document id are form inputs.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • 1
    On Stack Overflow it's expected that you make an attempt at writing code, and if it doesn't work, then show what you have and explain how it doesn't work the way you expect. I suggest starting with the [documentation](https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document). – Doug Stevenson Sep 02 '22 at 19:49

1 Answers1

0

You first need to use doc() function to create a DocumentReference for the documents and then use setDoc() function to add document in Firestore as mentioned in the documentation.

import { doc, setDoc } from "firebase/firestore"

// here db is getFirestore()
const docRef = doc(db, `User/${fields.user}/Address/${fields.address}`)

await setDoc(docRef, { test: "test" })

Alternatively you can use a batched write to add both the documents at once. Try refactoring the code as shown below:

import {
  writeBatch,
  doc
} from "firebase/firestore";

// Get a new write batch
const batch = writeBatch(db);

const docRef = doc(db, `User/${fields.user}/Address/${fields.address}`);
batch.set(docRef, {
  User: fields.user,
  Address: fields.address
});

const subDocRef = doc(db, `User/${fields.user}/Address/${fields.address}/Orders/${fields.ID}`);

batch.update(subDocRef, {
  ID: fields.ID
});

// Commit the batch
batch.commit().then(() => {
  console.log("Documents added")
}).catch(e => console.log(e));

Also checkout: Firestore: What's the pattern for adding new data in Web v9?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84