嗨,我正在创建一个空数组,然后使用 forEach 循环用 mongo 查询中的数据填充它。
我已经尝试了 4 天,但我似乎所做的一切都不起作用,我知道我很接近,但作为 javascript 和 MEAN 堆栈的新手,我只是无法弄清楚。
我已附上代码,并对我想做的所有事情进行注释。
请任何帮助都会很棒..
var mongoose = require('mongoose'),
User = require('../../models/UserModel'),
async = require('async');
module.exports.getfollowing = function(req, res){
//grab the Users ID from the body
var thefollower = req.body.follower;
//create empty array that i want to populate with the followee's ID and Avatar url
var obj = [];
//query mongo for the user
User.findOne({ _id: thefollower }, function (err, user) {
if (err) {
console.log(err);
res.json(err);
} else {
//grab the following element of the users mongo schema -- should return all the followee's ID's -- tested works
var following = user.following;
//iritate throught all the followee's
async.forEach(following, function(item, callback) {
//current followee
var user = item;
//query mongo for the followee
User.findOne({_id: user}, function(err, followee, callback){
//get followee's ID and Avatar url
var id = followee._id;
var avatar = followee.avatar;
//add the followee's ID and Avatar url to the obj array
obj.push({
id: id,
avatar: avatar
});
});
//see if this worked - returns empty
console.log(obj);
callback();
}, function(err) {
//see if this worked - returns empty
console.log(obj);
//respond to the client - returns empty
res.json(obj);
});
}
});
};
最佳答案
您需要将 async.forEach()
回调末尾的 callback();
移动到 User.findOne({ _id: user}, ...)
回调(在调用 obj.push()
之后),因为那是您实际完成 item
的时间。使用当前代码,您将立即告诉 async
模块您已经完成了 item
,然后您的 mongo 查询才有机会完成。
关于javascript - nodeJS 创建动态数组并用作响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34113862/