首页 > 解决方案 > 如何在 NodeJS 回调中获取 MongoDB 的 collection.aggregate() 的结果?

问题描述

我有以下users收藏:

{
    "_id" : ObjectId("5b29ba37cd0b1726068731c3"),
    "name" : "Gym Dog",
    "profilePicUrl" : "https://i.imgur.com/mPStaKV.png",
    "totalProgress" : {
    "goal" : 300,
    "progress" : 0,
    "percentage" : 0
    },
    "goals" : [
    {
        "description" : "Running",
        "goal" : 100,
        "progress" : 0,
        "percentage" : 0
    },
    {
        "description" : "Lifting",
        "goal" : 200,
        "progress" : 0,
        "percentage" : 0
    }
    ],
    "days" : [
    {
        "weekday" : "Sunday",
        "content" : ""
    },
    {
        "weekday" : "Monday",
        "content" : ""
    },
    {
        "weekday" : "Tuesday",
        "content" : ""
    },
    {
        "weekday" : "Wednesday",
        "content" : ""
    },
    {
        "weekday" : "Thursday",
        "content" : ""
    },
    {
        "weekday" : "Friday",
        "content" : ""
    },
    {
        "weekday" : "Saturday",
        "content" : ""
    }
    ],
    "activities" : [ ]
}

我想选择goals用户的第二个元素,Gym Dog然后在 NodeJS 回调函数中返回结果。


以下是我在Mongo shell中所做的:

db.users.aggregate(
    { $match: { name: 'Gym Dog' }},
    { $project: {
        _id: 0,
        ithGoal: { $arrayElemAt: [ '$goals', 1 ] }
    }}
).pretty()

Mongo shell 的结果。这也是我期望我的 NodeJS 代码输出的内容

{
    "ithGoal" : {
        "description" : "Lifting",
        "goal" : 200,
        "progress" : 0,
        "percentage" : 0
    }
}

以下是我在NodeJs中所做的:

mongoDB.collection('users').aggregate(
// pipeline
[
    { $match: { name: 'Gym Dog' }},
    { $project: {
        _id: 0,
        ithGoal: { $arrayElemAt: [ '$goals', 1 ] }
    }}
],
// callback
function(err, result) {
    if (err) {
        throw err
    }
    console.log(result);
});

但是,当result登录到控制台时,它是一个AggregationCursor {}带有一堆无关信息的对象。它与 Mongo shell 的输出没有任何相似之处(我在这里不包括输出,因为它太长了)。

我也试过mongoDB.collection('users').aggregate().toArray(function(err, result) {});了,但是它输出了整个 JSON 对象nameprofilePicUrl, totalProgress, goals, days, activitise(换句话说,它从我给出的条件中没有选择任何内容)。

所以,我的问题是,如何让 NodeJS 中的回调函数将与 Mongo shell 完全相同的结果存储到result参数中?

我正在使用 MongoDB 社区 3.6.5。提前致谢!

标签: javascriptnode.jsmongodb

解决方案


语法似乎正确。请检查 MongoDB 连接 URL。但我不确定,我想是一些与数据库连接相关的问题


推荐阅读