Ben*_*Ben 2 javascript firebase google-cloud-firestore
我试图通过字段值检索单个文档,然后更新其中的字段。当我这样做时,我将获得具有匹配.where("uberId", "==",'1234567')字段的所有文档。我确信这样的文件只有一份。但是,我不想使用 uberId 作为文档的 ID,否则我可以轻松地通过 ID 搜索文档。是否有另一种方法可以通过字段 ID 搜索单个文档?uberId1234567
到目前为止,阅读文档,我可以看到:
const collectionRef = this.db.collection("bars");
const multipleDocumentsSnapshot = await collectionRef.where("uberId", "==",'1234567').get();
Run Code Online (Sandbox Code Playgroud)
然后我想我可以做得到const documentSnapshot = documentsSnapshot.docs[0]唯一现有的文档参考。
但后来我想用以下内容更新文档:
documentSnapshot.set({
happy: true
}, { merge: true })
Run Code Online (Sandbox Code Playgroud)
我收到错误Property 'set' does not exist on type 'QueryDocumentSnapshot<DocumentData>'
虽然您可能知道只有一个文档具有给定uberId值,但 API 无法知道这一点。因此,API 对于任何查询都会返回相同的类型: a QuerySnapshot。您将需要循环遍历该快照中的结果才能获取文档。即使只有一个文档,您也需要该循环:
const querySnapshot = await collectionRef.where("uberId", "==",'1234567').get();
querySnapshot.forEach((doc) => {
doc.ref.set(({
happy: true
}, { merge: true })
});
Run Code Online (Sandbox Code Playgroud)
您的代码中缺少的是.ref:您无法更新DocumentSnapshot/,QueryDocumentSnapshot因为它只是数据库中数据的本地副本。因此,您需要调用ref它来获取数据库中该文档的引用。
| 归档时间: |
|
| 查看次数: |
6434 次 |
| 最近记录: |