如何在NodeJS回调中获得MongoDB的collection.aggregate()结果?

时间:2018-06-20 08:19:34

标签: javascript node.js mongodb

我有以下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的{​​{1}}的第二个元素,然后将结果返回到NodeJS回调函数中。


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

Gym Dog

来自Mongo Shell的结果。 这也是我期望NodeJS代码输出的结果

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

以下是我在 NodeJs 中所做的事情:

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

但是,当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对象,带有一堆不相关的信息。它与Mongo shell的输出没有任何相似之处(我在这里不包括输出,因为它太长了。)

我也尝试过AggregationCursor {},但是它输出了整个mongoDB.collection('users').aggregate().toArray(function(err, result) {});nameprofilePicUrltotalProgressgoalsdays(换句话说,它从我给出的条件中什么也没选择)。

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

我正在使用MongoDB社区3.6.5。预先感谢!

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

我也遇到了同样的问题,我通过验证查询中传递的 _id 是一个有效的 ObjectId 来解决它,您可以如下所示验证它。

import { ObjectId } from 'mongodb';
ObjectId.isValid(your_data_id) // Returns either true or false.
相关问题