jack blank jack blank - 6 months ago 24
MySQL Question

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 :


You are using asynchronous code synchronously


I was trying to fix that by using the below code. Don't know if this code will make it not sync but I heard that promises help with that.

so I have this and I cannot create(save) the data but I can delete it. why cant I use the same pattern for
create
as i did for
remove
?

var Comp = require("./models/company.js");
var arr = [
{name : "comp1",industry : "industry1", ranking: 20},
{name : "comp2",industry : "industry2", ranking: 5},
{name : "comp3",industry : "industry3", ranking: 10}
]


Comp.find({}).exec()
.then(function(docs){
return Comp.remove({}).exec()
.then(function(){
console.log("deleted")
})
})
.then(function(){
return Comp.create(arr).exec()
.then(function(data){
console.log(data)
})
})


and can you help get to my original goal which was in my other question.

Answer

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){
    ....
})