首页 > 解决方案 > 更新文档我不知道的文档ID云功能

问题描述

我正在尝试访问一个文档以更新它,但集合中只有一个文档,我不知道该文档的 ID,我如何知道那里有 w 才能访问它

return admin.firestore().collection('users').doc(uid).collection('score').doc().update({
   points: admin.firestore.FieldValue.increment(10),
})

此代码不起作用,我收到错误:没有要更新的文档。

我理解这是因为调用 .doc() 方法只会生成一个随机 ID。那么如何访问文档呢?

标签: typescriptgoogle-cloud-functions

解决方案


如果您知道该文档的确切路径,则只能在 Firestore 中更新该文档。如果您还不知道路径,则必须阅读文档才能确定。

如果要更新集合中的所有文档,这意味着您只需调用get()集合即可获取所有文档。即使只有一个文档,您仍然必须更新所有文档。

代码看起来像这样:

let collectionRef = admin.firestore().collection('users');
collectionRef.get().then(snapshot => {
  snapshot.forEach(doc => {
    doc.update({
      points: admin.firestore.FieldValue.increment(10),
    })
  });
})
.catch(err => {
  console.log('Error getting documents', err);
});

另请参阅获取集合中所有文档的文档


如果您在 Cloud Function 或其他无法处理 Promise 的环境中使用它,则需要冒泡结果:

let collectionRef = admin.firestore().collection('users');
return collectionRef.get().then(snapshot => {
  return Promise.all(snapshot.documents.map(doc => {
    return doc.update({
      points: admin.firestore.FieldValue.increment(10),
    })
  }));
})

推荐阅读