Monday, 13 March 2017

MongoDB, Aggregate $match not working on ObjectId

I have a schema that is:

var photoSchema = new mongoose.Schema({
    id: String,     // Unique ID identifying this photo
    file_name: String,
    date_time: {type: Date, default: Date.now},
    user_id: mongoose.Schema.Types.ObjectId, // The user id of the user who created the photo.
    comments: [commentSchema] // Comment objects representing the comments made on this photo.
});

var Photo = mongoose.model('Photo', photoSchema);

I am trying to find the photo from a specific user with most number of comments. Here is what I have done:

Photo.aggregate([
        {
            $project: {
                id: 1,
                file_name: 1,
                date_time: 1,
                user_id: 1,
                comments: 1,
                length: {$size: "$comments"}
            }
        },
        {
            $match: {
                user_id: mongoose.Schema.Types.ObjectId(request.params.id)
            }
        },
        {
            $sort: { length: -1 }
        }
        ], function (err, info2){
            if (err) {
                    // Query returned an error.
                    console.error('Doing /user/usage/:id error:', err);
                    response.status(400).send(JSON.stringify(err));
                    return;
            }
            console.log(info2);
            finalOutput.most_commented = info2[0];
            response.end(JSON.stringify(finalOutput));
        });

I only get an empty array [] in the console.log, I know the $match is not working because if I remove $match clause, it gives me the photo with max comments across the entire table. I want to filter and get the photo which belong to 1 specific user, based on their user_id.

I don't understand what I am doing wrong. I have tried:
1. $match: {user_id: mongoose.Schema.Types.ObjectId(request.params.id)}
2. $match: {user_id: request.params.id}
3. $match: {"user_id": request.params.id}



via BNKS

No comments:

Post a Comment