Firestore-检查是否存在要更新的文档 [英] Firestore - Check if the document which is being updated exists

查看:59
本文介绍了Firestore-检查是否存在要更新的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知-为了检查document是否存在,我应该使用get函数并查看它是否存在.

As far as I know - In order to check whether a document exists or not, I should use the get function and see if it does.

我的问题是关于更新时进行检查-是否可以?(考虑到document在更新发生时可能会消失).

My question is about checking while updating - Is it possible? (Considering that the document might be gone when the update occurs).

我试图更新一个空的document,但出现一个错误,提示该文档不存在,但我认为这可能不是检查此文档的成功方法.

I have tried to update an empty document and I got an error which says that the document doesn't exist, but I think this might not be the successful way to check this.

推荐答案

有几种方法可以将数据写入Cloud Firestore:

There are a few ways to write data to Cloud Firestore:

  • update()-更改文档中已存在的字段.如果文档不存在,则失败.
  • set()-覆盖文档中的数据,如果尚不存在则创建该文档.如果您只想部分更新文档,请使用SetOptions.merge().
  • create()-仅在服务器端SDK中可用,类似于set(),但如果文档已存在则失败.
  • update() - change fields on a document that already exists. Fails if the document does not exist.
  • set() - overwrite the data in a document, creating the document if it does not already exist. If you want to only partially update a document, use SetOptions.merge().
  • create() - only available in the server-side SDKs, similar to set() but fails if the document already exists.

因此,您只需要针对用例使用正确的操作即可.如果要在不知道文档是否存在的情况下更新文档,则要使用带有merge()选项的set(),如下所示(此示例适用于Java):

So you just need to use the correct operation for your use case. If you want to update a document without knowing if it exists or not, you want to use a set() with the merge() option like this (this example is for Java):

// Update one field, creating the document if it does not already exist.
Map<String, Object> data = new HashMap<>();
data.put("capital", true);

db.collection("cities").document("BJ")
        .set(data, SetOptions.merge());

这篇关于Firestore-检查是否存在要更新的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆