云数据库,如何判断doc是否存在
发布于 4 年前 作者 xiuyingshi 15219 次浏览 来自 问答

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 回复

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

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

就能搞定

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

db.collection('xxx').where({  _id: 'xxxid'}).get()
回到顶部