云数据库,如何判断doc是否存在

发布于 6 年前作者 xiuyingshi15449 次浏览最后编辑 6 年前来自 ask

db.collection('xxx').doc('xxxid').get()

上面如果 xxxid 不存在,会抛错:

{"errCode":-1,"errMsg":"document.get:fail document with _id xxxid does not exist; at document.get api; "}}

请问正确判断doc是否存在正确方式是什么?

1 回复
mingshen
mingshen1 楼4 年前

这要看你的具体场景,如果是需要判断doc是否存在并且需要更新操作,那么

db.collection('xxx').doc('xxxid').set()

就能搞定

如果只是单纯的判断doc是否存在不做更新操作,那么加上try … catch捕获这个错误或者改用

db.collection('xxx').where({  _id: 'xxxid'}).get()