javascript - 如果文档已存在 firestore 批处理,则阻止更新
问题描述
我有一个程序在firestore上对集合执行批量写入。
我仅在集合中不存在 is 时才尝试编写文档,如果存在则跳过而不修改任何内容。
安全规则如下:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /collection/{id} {
allow create,delete: if request.auth.uid != null;
}
}
}
在测试工具上进行测试时,它按预期工作。我只被允许在这个集合中创建和删除文档。但是,当从程序运行时,如果已经存在,批量写入能够修改文档字段(在这种情况下为戳记)。
代码如下:
var batch = firestore.batch();
var docRef= firestore.collection("collection").doc(data.id);
batch.set(
docRef,{
id: data.id,
stamp: new Date(),
},
);
我错过了什么,或者做错了什么?
解决方案
您可以先检查文档是否存在,然后仅在不存在时才写入
docRef.get().then(doc => {
if (!doc.exists) {
batch.set(docRef, {
id: data.id,
stamp: new Date(),
});
}
});
推荐阅读
- linux - 如何在 github 上上传 Python 脚本
- apache-camel - 从 Camel Rest 下载的文件为空
- java - 从 hashMap 值中获取 id 列表的最佳方法
- reactjs - 如何在反应状态下将 HTML 存储为对象属性的值?
- scala - 重新定位,现在面临 Scala 依赖问题
- java - Java Eclipse - 未定义的构造函数和方法
- python - 更改数据框中的值
- c++ - 为什么 std:set (带有单个冒号)可以编译?
- xml - 使用 Resources.resx 在 MVVM 的视图中显示越南语和中文(多语言)
- mysql - SQL Join 并获取表中的计数