我有几个有趣的问题。我正在使用猫鼬和node.js 假设我有一个称为Actor的架构,所有问题都将与之相关。
1)const saveActor = await Actor.save();
这是否始终引发异常,还是像下面这样强制检查和预防措施? :
if(saveActor) return "success"; else return "error"; ?
2)const actor = Actor.findByIdAndUpdate("5ca509acd0ddef4d1c1c892f", someotheroptions);
如果未找到,则返回null。因此,我必须检查它是否返回null-这是否意味着找不到该文档?那更新呢?如果更新不起作用怎么办-它会一直抛出异常还是有时返回null?
3)其他猫鼬功能又如何呢? findByIdAndRemove
?总和是多少?他们是否一直或有时抛出异常?我在文档中找不到此信息。
答案 0 :(得分:1)
1:const saveActor = await Actor.save()
。
saveActor
将包含成功返回值。如果发生错误,它将引发您必须捕捉的错误。对于async/await
语法,它的完成方式是:
try {
const saveActor = await Actor.save();
} catch (e) {
console.error(e)
}
2:const actor = Actor.findByIdAndUpdate("5ca509acd0ddef4d1c1c892f", someotheroptions)
如果查询成功:
如果发生错误,则引发错误。如果您使用的是callback
,则会将错误作为参数传递给回调。如果您使用的是thenables
或Promise
/ async await
,则必须catch
。
3:不同的方法具有不同的返回类型。例如(来自文档):
Mongoose.prototype.model()
Returns:
«Model» The model associated with name. Mongoose will create the model if it doesn't already exist.
Model.find()
Returns:
«Query»
错误
对于错误,通常来说,如果该方法接受回调,则error是类似(err, doc) => { if (err) console.error(err) ... }
的参数
如果未传递回调,则通常为thenables
或Promise
(more here)。其处理方式类似于Actor.findByIdAndUpdate("5ca509acd0ddef4d1c1c892f", someotheroptions).then(data => console.log(data)).catch(err => console.error(err))
等。
完整mongoose API。向MDN咨询Promise
和async/await