我有一个数据集,如下所示:
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
,但我不知道如何理解它。