FireStore创建文档(如果不存在) [英] FireStore create a document if not exist

查看:54
本文介绍了FireStore创建文档(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要更新这样的文档:

db.collection('users').doc(user_id).update({foo:'bar'})

但是,如果doc user_id不存在,则上面的代码将引发错误.因此,如何告诉Firestore创建学生(如果不存在),换句话说,是这样的:

However, if the doc user_id does not exists, the above code will throw an error. Hence, how to tell Firestore to create the student if not exists, in other word, behave like this:

db.collection('users').doc(user_id).set({foo:'bar'})

推荐答案

我认为您想使用以下代码:

I think you want to use this code:

db.collection('users').doc(user_id).set({foo:'bar'}, {merge: true})

这将使用提供的数据设置文档,并使其他文档字段保持不变.最好不确定文档是否存在.只需将选项合并与任何现有文档合并,即可避免覆盖整个文档.

This will set the document with the provided data and will leave other document fields intact. It is best when you're not sure whether the document exists. Simply pass the option to merge the new data with any existing document to avoid overwriting entire documents.

有关使用Firestore管理数据的更多详细信息,请参见此链接

这篇关于FireStore创建文档(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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