1

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.

black_sheep07
  • 2,308
  • 3
  • 26
  • 40
  • 1
    It doesn't appear that `details` is an array of subdocuments so why are you unwinding it and not simply matching on the full path? If your mongoose schema has typed it as an ObjectId, then it should work fine. What does the associated `Running` schema look like? – Jason Cust Aug 18 '17 at 21:04
  • Why do you need an aggregation for this action? Looks to me like it can be solved with a simple 'find' query and projection. – ryder Aug 19 '17 at 05:30

0 Answers0