返回Model.create(arr).exec()不工作在mongoose

我听说exec“返回一个承诺”,所以我使用exec它做asynchronous调用。 这个问题激发了我的另一个问题 。 评论员说我的代码不工作,因为:

您正在同步使用asynchronous代码

我试图通过使用下面的代码来解决这个问题。 不知道这个代码是否会使它不同步,但我听说承诺有帮助。

所以我有这个,我不能创build(保存)的数据,但我可以删除它。 为什么不能像我一样使用相同的模式来create

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

你能帮我达到我原来的目标吗?

thenfunction不回诺, exec呢!

所以你需要做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){ .... }) 

首先你应该确认你的mongoose版本。

在旧版本中:

Model.create(doc)返回一个查询对象; 调用查询的exec方法将触发数据库操作并返回一个promise。

在新版本(我使用4.4.8 )mongoose Model.create(doc)和'Model.remove(con)'直接返回一个promise。

所以检查你的版本,看看你是否需要删除一些exec

最后但并非最不重要的添加catch调用来检查是否有一些错误,它有助于debugging

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