Mongoose - 使用聚合框架

时间:2017-08-18 17:44:42

标签: mongodb mongoose aggregation-framework

我有一个数据集,如下所示:

db.running.insert({
    "_id" : ObjectId("59960ba78fe25d08f4664d6a"),
    "person" : "Peter",
    "place" : "State Street",
    "eventDate" : ISODate("2017-08-17T00:00:00Z"),
    "thing" : "Running",
    "details" : {
            "distance" : "2 miles",
            "area" : "City Center",
            "_id" : ObjectId("599636f8ea4d7835be869728")
        }
    })

我正在尝试使用aggregate运行查询,该查询根据其id找到子文档。以下是可正常工作的shell代码:

db.running.aggregate([
    { $unwind: '$details'},
    { $match: {'details._id': ObjectId("599636f8ea4d7835be869728") } },
    { $project: {'thing': 0}}
]).pretty()

使用mongoose,我的代码如下所示:

var Running = mongoose.model('Running');
mongoose.set('debug', true);

var sendJSONresponse = function(res, status, content) {
  res.status(status);
  res.json(content);
};

module.exports.getPageGradedData = function (req, res){
    Running
        .aggregate([
            { $unwind: '$details'},
            { $match: {'details._id': req.params.detailid } },
            { $project: {'thing': 0}}
        ])
        .exec(function(err, response) {
            sendJSONresponse(res, 200, response);
    });
};

但是,mongoose的调试显示mongoose发送给mongoDB的查询如下所示:

Mongoose: running.aggregate([ { '$unwind': '$details' }, { '$match': { 'details._id': '599636f8ea4d7835be869728' } }, { '$project': { thing: 0 } } ], {})

Mongoose显然不明白details._id对象需要转换为ObjectId,但我不知道如何理解它。

0 个答案:

没有答案