返回Model.create(arr).exec()在猫鼬中不起作用 [英] return Model.create(arr).exec() is not working in mongoose
问题描述
我听说exec兑现了承诺",所以我正在使用exec进行异步调用.这个问题是我其他问题的启发.解说员说我的代码不起作用,因为:
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.
所以我有这个,我不能创建(保存)数据,但是可以删除它.为什么不能为create
使用与remove
相同的模式?
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.
推荐答案
then
函数不返回承诺, 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){
....
})
这篇关于返回Model.create(arr).exec()在猫鼬中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!