简体   繁体   English

有没有办法在 firebase 9 中写这个 firebase 8 function ?

[英]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.我得到了这个 function 来将数据添加到 Firestore 数据库,并且想知道如何在较新的版本中做到这一点。

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.这个 function 是在一个集合中添加一个包含数据的文档,然后创建一个具有不同文档的子集合,其中包含自己的数据。 The document id are form inputs.文档 ID 是表单输入。

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 .您首先需要使用doc() function 为文档创建DocumentReference ,然后使用setDoc() function 在 Firestore 中添加文档,如文档中所述。

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?另请查看: Firestore:在 Web v9 中添加新数据的模式是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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