我想知道何时使用exec,然后知道差异
Schema.findOne({_id:id}).then(function(obj){
//do somthing
})
或使用exec
Schema.findOne({_id:id}).exec().then(function(obj){
//do somthing
})
答案 0 :(得分:0)
Mongoose的某些方法返回查询但不执行其他直接执行。
仅返回查询时使用exec()。
'then'在执行后用作承诺处理程序。
您可以在执行后使用'then and catch'或回调。
有一个使用promise的例子和使用回调的例子。
Cat.find({})
.select('name age') // returns a query
.exec() // execute query
.then((cats) => {
})
.catch((err) => {
});
Cat.find({})
.select('name age') // returns a query
.exec((err,cats) => { // execute query and callback
if(err){
} else {
}
});
现在让我们在没有查询的情况下做同样的事情(不要选择字段,不需要exec,因为已经是exec)
Cat.find({})
.then((cats) => {
})
.catch((err) => {
});
Cat.find({}, (err,cats) => {
if(err){
} else {
}
});