Return Model.create(arr).exec() Is Not Working In Mongoose
I heard that exec 'returns a promise' so I'm using exec it do asynchronous calls. This question is inspired my other question. The commentator said my code is not working because
Solution 1:
The then funtion does not return promise, the exec does!
So you need to do return Comp.remove({}).exec()
Comp.find({}).exec()
.then(function(docs){
return Comp.remove({}).exec();
})
.then(function(result_of_remove){
return Comp.create(arr).exec();
})
.then(function(result_of_create){
....
})
Solution 2:
first of all you should confirm you mongoose version.
in older version:
Model.create(doc) returns a query object; call the exec method of the query will trigger the database operation and return a promise.
in new version (i am using 4.4.8) of mongooseModel.create(doc) and 'Model.remove(con)' returns a promise directly.
so check with your version to see if you need to remove some exec
last but not least add catch call to check if you got some errors, it helps when debug
Comp.find({}).exec()
.then(function(docs){
return Comp.remove({}).exec();
})
.then(function(result_of_remove){
return Comp.create(arr).exec();
})
.then(function(result_of_create){
....
})
.catch(function(error){
console.log(error)
})
Solution 3:
I normally use .exec() when I want to return a Promise when working with
Model.findOne(...).exec()
Model.create(...) returns a Promise.
The .exec() function does not exist for Model.create(...)
Post a Comment for "Return Model.create(arr).exec() Is Not Working In Mongoose"