i wanna know when to use exec or then, and what's the difference
Schema.findOne({_id:id}).then(function(obj){
//do somthing
})
or to use exec
Schema.findOne({_id:id}).exec().then(function(obj){
//do somthing
})
i wanna know when to use exec or then, and what's the difference
Schema.findOne({_id:id}).then(function(obj){
//do somthing
})
or to use exec
Schema.findOne({_id:id}).exec().then(function(obj){
//do somthing
})
Some methods of Mongoose returns a query but not execute others execute directly.
When returns only a query use exec().
'then' is used as promise handler after execution.
You can use 'then and catch' or callback after execution.
There is an example using promise and the same using callback.
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 {
}
});
Now lets make same without query(don't select fields, don't need to exec, because is already exec)
Cat.find({})
.then((cats) => {
})
.catch((err) => {
});
Cat.find({}, (err,cats) => {
if(err){
} else {
}
});