Firebase Cloud Firestore创建条目或更新(如果已存在) [英] Firebase Cloud Firestore create entry or update if it already exists

查看:131
本文介绍了Firebase Cloud Firestore创建条目或更新(如果已存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个问题,知道何时向Firebase Firestore数据库添加或更新条目.

I have an issue of knowing when to add or update an entry to a Firebase Firestore database.

使用doc_ref.set将添加一个文档(如果该文档不存在).如果已经存在并调用set,它将覆盖所有文档字段.

Using doc_ref.set will add a document if it does not exist. It will also override all of a documents fields if it already exists and set is called.

如果文档存在,使用doc_ref.update将更新文档的字段.如果该文档不存在,则什么也不会发生.

Using doc_ref.update will update fields of a document if the document exists. If the document does not exist, nothing happens.

如果该字段当前不存在,如何将新字段添加到文档中;如果该字段存在,则如何更新该字段?我可以读取数据库并检查该字段是否存在,然后使用setupdate,但是肯定有更简单的方法吗?

How do I add a new field to a document if the field does not currently exist, or update the field if it does exist? I could read the database and check if the field exists, and then use either set or update, but surely there is an easier way?

推荐答案

您要查找的是set操作中的merge选项.从设置文档上的文档:

What you're looking for is the merge option in the set operation. From the documentation on setting a document:

var cityRef = db.collection('cities').doc('BJ');

var setWithMerge = cityRef.set({
    capital: true
}, { merge: true });

如果不确定文档是否存在,请传递选项以将新数据与任何现有文档合并,以避免覆盖整个文档.

If you're not sure whether the document exists, pass the option to merge the new data with any existing document to avoid overwriting entire documents.

这篇关于Firebase Cloud Firestore创建条目或更新(如果已存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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