繁体   English   中英

为什么循环中的Mongoose查询仅返回第一个结果?

[英]Why is my Mongoose query within a loop only returning the first result?

我已经为此苦苦挣扎了好几天了。 我正在尝试返回ID列表引用的数据。

一个团队的JSON示例:

 {  
   "Name":"Team 3",
   "CaptainID":"57611e3431c360f822000003",
   "CaptainName":"Name",
   "DateCreated":"2016-06-20T10:14:36.873Z",
   "Members":[  
      "57611e3431c360f822000003", //Same as CaptainID
      "57611e3431c360f822000004" //Other members
   ]
}

这是路线:

router.route('/teams/:user_id')
.get(function (req, res) {

    TeamProfile.find({
        Members : {
            $in : [req.params.user_id]
        }
    }).exec(function (err, teamProfiles) {

        teamProfiles.forEach(function (teamProfile) {

            UserProfile.find({
                UserID : {
                    $in : teamProfile.Members.map(function (id) {
                        return id;
                    })
                }
            }, function (err, userProfiles) {           
                teamProfile.Members = userProfiles;
                console.log(teamProfile); //will console log the remaining 2
            })
            .exec(function (err) {              
                res.json(teamProfile) //returns the first one only
            })
        })
    });
})

这个想法是通过仅使用ID来获取最新数据的途径来返回配置文件。

但是,它正在发挥作用。 它获取用户信息以及所有信息,但不返回代码中注释的所有Teams +所有用户。 共有3个团队。 仅返回第一个。 如果我删除res.json(teamProfile)它的控制台将记录所有3个团队。 我想归还所有3支队伍。

这是因为在完成所有数据库操作之前都会调用您的响应。 因此,而不是每个使用async.forEach函数。 安装异步模块

var  async = require('async');
router.route('/teams/:user_id').get(function (req, res) {

TeamProfile.find({
    Members : {
        $in : [req.params.user_id]
    }
}).exec(function (err, teamProfiles) {

    async.forEach(teamProfiles,function (teamProfile,cb) {

        UserProfile.find({
            UserID : {
                $in : teamProfile.Members.map(function (id) {
                    return id;
                })
            }
        }, function (err, userProfiles) {           
            teamProfile.Members = userProfiles;
            cb() // Callback
        })

    },function(){
       res.json(teamProfiles) 
    })
});
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM