【问题标题】:How to read property of undefined object from MongoDB aggregation?如何从 MongoDB 聚合中读取未定义对象的属性?
【发布时间】:2023-03-30 09:16:01
【问题描述】:

我正在使用 NodeJS/ExpressJS 和 MongoDB 构建一个由两个团队和用户组成的寻宝网络应用程序。每个用户都有个人分数,这些分数会添加到团队分数中。我想在仪表板视图上显示两个团队的总分。我使用 MongoDB 的聚合框架来查询数据库。这是可以正常工作并返回对象数组的代码。

module.exports.getTotalTeamScore = function () {
   User.aggregate([
        { $group: {
            _id: "$team",
            total: { $sum: "$score"}
        }}
    ], function (err, results) {
        if (err) {
            console.error(err);
        } else {
            console.log(results);
            return results;
        }
    }
   );
}

我在用户模型文件中创建了这个函数。现在,当我通过

从某个路由文件中调用此函数时

var teamsObj = User.getTotalTeamScore();,

它确实给出了如下的对象数组,但是它是未定义的。

[ { _id: 'Team Black', total: 40 },
{ _id: 'Team Red', total: 60 } ]

问题是我无法在路由文件中做这样的事情。 (我可以在存在getTotalTeamScore 函数的用户模型文件中正常访问它):

teamsObj[0].total

我得到的错误是TypeError: Cannot read property 'total' of undefined

请帮我解决这个问题。我还是 NodeJS/ExpressJS 和 MongoDB 的新手,想学习。

谢谢

【问题讨论】:

  • 告诉我你是如何从其他路由文件调用这个函数 getTotalTeamScore 的。粘贴您的代码。您的 getTotalTeamScore 有问题,它返回结果的方式。
  • 添加到原始问题

标签: node.js mongodb express mongoose aggregation-framework


【解决方案1】:

您的函数 getTotalTeamScore 正在执行异步操作的 mongodb 聚合函数。

因此它不会立即返回结果,但您的函数将在聚合返回数据库记录之前返回。 所以你需要使用回调。

首先像这样修改你的getTotalTeamScore函数:

module.exports.getTotalTeamScore = function (callback) {
   User.aggregate([
        { $group: {
            _id: "$team",
            total: { $sum: "$score"}
        }}
    ], function (err, results) {
        if (err) {
            callback(err);
            console.error(err);

        } else {
            console.log(results);
            callback(null, results);
        }
    }
   );
}

然后像这样调用:

User.getTotalTeamScore(function (err, records) {
    if (err) {
        // Handle Error
    } else {
       teamsObj = records; 
       // Further Processing.
    }
});

【讨论】:

  • 非常感谢。您的解决方案 100% 正确并解决了问题。
猜你喜欢
  • 1970-01-01
  • 2018-06-12
  • 2015-03-06
  • 2019-12-01
  • 2018-10-04
  • 2020-11-11
  • 2021-04-30
  • 2016-05-24
  • 1970-01-01
相关资源
最近更新 更多