javascript - nodeJS 创建动态数组并用作响应

标签 javascript arrays node.js mongodb express

嗨,我正在创建一个空数组,然后使用 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/

相关文章:

javascript - 如何使用express和handlebar或其他模板引擎在node.js中渲染rest api调用?

javascript - Node.js 错误(NPM 错误)

javascript - 如果回调调用封闭函数,它会被称为递归调用吗?

javascript - jQuery - 从索引中获取子项作为 jQuery 对象

javascript - AngularJS 希伯来语日期转换器

javascript - Chrome 扩展程序如何收到后台脚本要关闭的通知?

node.js - 如何解决云函数中的 firestore 批处理限制

javascript - 如何将数据精确地推送到数组中所需的索引

java - 在二维数组中累积行

javascript - jQuery Ajax 传递带有预定义变量的数组