typescript - 更新文档我不知道的文档ID云功能
问题描述
我正在尝试访问一个文档以更新它,但集合中只有一个文档,我不知道该文档的 ID,我如何知道那里有 w 才能访问它
return admin.firestore().collection('users').doc(uid).collection('score').doc().update({
points: admin.firestore.FieldValue.increment(10),
})
此代码不起作用,我收到错误:没有要更新的文档。
我理解这是因为调用 .doc() 方法只会生成一个随机 ID。那么如何访问文档呢?
解决方案
如果您知道该文档的确切路径,则只能在 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),
})
}));
})
推荐阅读
- git - 正确设置文件夹中的 .gitignore 文件
- c# - Visual Studio Mac Intellisense 在按下回车键时生成新行而不是完成文本
- c - 赢得猜字游戏时无法终止 for 循环
- laravel - 在 Laravel 中获取空数据
- aws-lambda - aws sam 发布/部署流程
- swift - 如果 Swift 协议是用类型约束定义的,为什么不能直接访问该类型的属性/方法?
- excel - 通过 FTP 发布 Excel 加载项
- android - 未调用 AndroidManifest 中设置的活动
- java - 如何在环境变量中赋予多个系统变量相同的优先级?
- spring - 将对象从 thymeleaf 模板发送到 Rest Controller 返回“不支持的媒体类型”