I have a data set, as follows:
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")
}
})
I am trying to run a query using aggregate
that finds the subdocument based on its id
. Here is the shell code that works correctly:
db.running.aggregate([
{ $unwind: '$details'},
{ $match: {'details._id': ObjectId("599636f8ea4d7835be869728") } },
{ $project: {'thing': 0}}
]).pretty()
Using mongoose, my code looks like this:
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);
});
};
However, the debug from mongoose
shows the query that mongoose
is sending to mongoDB
to look like this:
Mongoose: running.aggregate([ { '$unwind': '$details' }, { '$match': { 'details._id': '599636f8ea4d7835be869728' } }, { '$project': { thing: 0 } } ], {})
Mongoose clearly doesn't understand that the details._id
object needs to be transformed to an ObjectId
, but I'm not sure how to get it to understand that.