【发布时间】:2015-12-06 12:39:11
【问题描述】:
您好,我正在创建一个空数组,然后使用 forEach 循环使用来自 mongo 查询的数据填充它。
我现在已经尝试了 4 天,但我似乎没有做任何工作,我知道我很接近,但作为 javascript 和 MEAN 堆栈的新手,我只是想不通。
我在我想做的所有事情上都附上了带有 cmets 的代码。
任何帮助都会很棒..
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);
});
}
});
};
【问题讨论】:
标签: javascript arrays node.js mongodb express