admin管理员组

文章数量:1396802

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.
    ments: [mentSchema] // Comment objects representing the ments 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 ments. Here is what I have done:

Photo.aggregate([
        {
            $project: {
                id: 1,
                file_name: 1,
                date_time: 1,
                user_id: 1,
                ments: 1,
                length: {$size: "$ments"}
            }
        },
        {
            $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_mented = 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 ments 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}

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.
    ments: [mentSchema] // Comment objects representing the ments 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 ments. Here is what I have done:

Photo.aggregate([
        {
            $project: {
                id: 1,
                file_name: 1,
                date_time: 1,
                user_id: 1,
                ments: 1,
                length: {$size: "$ments"}
            }
        },
        {
            $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_mented = 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 ments 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}

Share Improve this question asked Mar 13, 2017 at 20:13 BNKSBNKS 612 silver badges9 bronze badges 5
  • Can you take a look at this ?stackoverflow./questions/16310598/… – s7vr Commented Mar 13, 2017 at 20:25
  • 1 ^^ Thanks! Turns out the casting of the ObjectId seemed to be the issue. It was being cast using the Schema type Object Id mongoose.Schema.Types.ObjectId when it needed to be just a pure ObjectId mongoose.Types.ObjectId. (Source: stackoverflow./a/16312935/5382718) – BNKS Commented Mar 13, 2017 at 20:31
  • I spent hours last night on this, so silly! :D – BNKS Commented Mar 13, 2017 at 20:31
  • Possible duplicate of unable to use $match operator for mongodb/mongoose aggregation with ObjectId – s7vr Commented Mar 13, 2017 at 20:31
  • @BNKS it's looks like very slimier, almost duplicate, can you please self care of it to make site clean :) – Abdul Hameed Commented Apr 25, 2018 at 13:55
Add a ment  | 

2 Answers 2

Reset to default 6

First Step

const ObjectId = require('mongoose').Types.ObjectId

Second Step

{ $match : { _id: ObjectId("606c74d5f9e3f30f8caa3451")} }

Id variable would be constructed of "strings", and not ObjectId values. Mongoose "autocasts" string values for ObjectId into their correct type in regular queries but not in aggregation. More details - https://github./Automattic/mongoose/issues/1399

That's why you need to do the casting in the code itself.

{ $match : { _id: mongoose.Types("606c74d5f9e3f30f8caa3451")} }

(Don't forget to import mongoose)

本文标签: javascriptMongoDBAggregate match not working on ObjectIdStack Overflow