假设,我有一个模型,其中包含传入的值数组,
[ { _id: 5a69e13780e4172d514ed906, hobbyname: 'Teaching', __v: 0 },
{ _id: 5a69e1477a40892d6416f906, hobbyname: 'Cricket', __v: 0 }]
var arr = [];
for(var i=0; i < someModel.length; i++){
Hobby.find({})
.then(function(hob){
arr[i] = someModel[i].hobbyname;
})
.catch(function(err){
console.log(err);
});
}
console.log(arr);
目前它的日志记录为[]
,我希望它完成查询执行,将值推送到arr
,然后给我结果。
我简化了我的项目场景,只是为了使其易于理解,我是一个新人,需要帮助,提前致谢。
最佳答案
所有数据处理都应该在回调函数中
Hobby.find({})
.then(function(hob){
console.log(hob);
//here **hob** already contains the result of Mongo query - it's an array
//so put your processing code here
})
.catch(function(err){
console.log(err);
});
如果你想通过id或其他条件从Mongo捕获数据,你需要在查找查询中设置这样的条件 更新: 或者您可以使用async.waterfall获取数据后进行处理
async.waterfall(
[
function(callback) {
Hobby.find({})
.then(function(hob){
console.log(hob);
return callback(null, hob);
})
.catch(function(err){
console.log(err);
return callback(err);
});
},
function(hobbies, callback) {
//here you get all retrieved hobbies to work on
//**hobbies** - is result array
//you may process it here
return callback(null, hobbies);
}
],
function(err, result) {
if (err) {
console.log(err);
}
return next();
}
);
关于javascript - 在 for 循环中执行的 Mongoose 查询在完成执行后不会被插入空数组,nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48446142/