首页 > 解决方案 > 如果文档已存在 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(),
    },
);

我错过了什么,或者做错了什么?

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


您可以先检查文档是否存在,然后仅在不存在时才写入

docRef.get().then(doc => {
    if (!doc.exists) {
        batch.set(docRef, {
            id: data.id,
            stamp: new Date(),
        });
    }
});

推荐阅读