简体   繁体   中英

Is there a way to write this firebase 8 function in firebase 9?

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM