如何在firestore中创建自定义id文档(Firebase模块化SDK(v9))

Ash*_*wal 2 javascript firebase google-cloud-firestore

我们如何使用新的模块化 SDK V9 在 firestore 中创建具有自定义 id 的文档?

const register = async function (adminEmail){
  try{
    const docSnap = await getDoc(availableIdRef);
    const collegeId = docSnap.data().id; //This should be the document id

    const adminRef = collection(firestore, 'admin');
    await addDoc(adminRef, {adminEmail, collegeId});

  }catch(e){
    alert("Error!");
  }
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个 id 为集合的新collegeId文档admin

我知道如何在 Web 版本 8(命名空间)中执行此操作,但不知道 Web 版本 9(模块化)。

Dha*_*raj 5

您可以使用setDoc()方法指定 ID,而不是addDoc生成随机 ID,如文档中所述:

const adminRef = doc(firestore, 'admin', collegeId);
//       doc  --->^
await setDoc(adminRef, {email: adminEmail, id: collegeId}) // overwrites the doc if it already exists
//    ^^^
Run Code Online (Sandbox Code Playgroud)

另请注意,要创建DocumentReference您需要使用doc()而不是collection()用于创建CollectionReference。我在这里解释了这两者的区别:Firestore:在 Web v9 中添加新数据的模式是什么?