【问题标题】:Why is my Mongoose query within a loop only returning the first result?为什么我在循环中的 Mongoose 查询只返回第一个结果?
【发布时间】:2016-10-21 14:27:19
【问题描述】:

我已经为此苦苦挣扎了好几天。我正在尝试返回由 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 来获取最新数据来返回配置文件。

但是,它在一定程度上发挥了作用。它获取用户信息和所有信息,但不返回代码中注释的所有团队 + 所有用户。总共有3支球队。只返回第一个。如果我删除 res.json(teamProfile) 它控制台会记录所有 3 个团队。我想返回所有 3 个团队。

【问题讨论】:

  • 使用异步函数获取结果

标签: json node.js mongodb mongoose mean-stack


【解决方案1】:

这是因为在完成所有数据库操作之前调用了您的响应。所以不要为每个使用 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) 
    })
});
})

【讨论】:

  • 谢谢!我知道这与完成所有操作有关。你的回答有一个小错别字。它是 res.json(teamProfiles)。成就了我的一天! :)
猜你喜欢
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 2019-10-06
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2013-10-27
  • 2020-11-25
相关资源
最近更新 更多