Mongoose aggregate returns empty result

I have problems requesting a mongoose aggregate.

It kind of drives me crazy because I can't find a solution anywhere. I would really appreciate any support.

Scheme:

var EvalSchema = new Schema({
modified: {type: Date, default: Date.now},
created : {type: Date, default: Date.now},
username: {type: String, required: true},
item: {type: String, required: true},
criteria: [
    {
        description: {type: String},
        eval: {type: Number}
    }
]});mongoose.model('Eval', EvalSchema);

and I use aggregation to calculate the sum of the ratings for each criterion for a given element.

Eval.aggregate(
[
        { $match: { item:  item.id}},
        { $unwind : "$criteria" },
        { 
            $group: { 
                    _id: "$criteria.description", 
                    total: { $sum: "$criteria.eval" },
                    count: { $sum: 1 }
                }
        },
        {$project: {total:1, count:1, value: { $divide: [ "$total", "$count" ]}}}
    ], function (err, result) {
    if (err) {
        console.log(err);
    }
        console.log(result);
    });

The result is always empty ....

I log all requests that apply to mongoose fire in the application. When I run the query in Mongodb, it returns the correct result.

coll.aggregate([ { '$match': { item: 'kkkkkkkkkkk' } }, { '$unwind': '$criteria' }, { '$group': { _id: '$criteria.description', total: { '$sum': '$criteria.eval' }, count: { '$sum': 1 } } }, { '$project':               { total: 1, count: 1, value: { '$divide': [ '$total', '$count' ] } } } ]) 

Result:

{
    "result" : [
            {
                    "_id" : "Overall satisfaction",
                    "total" : 4,
                    "count" : 1,
                    "value" : 4
            },
            {
                    "_id" : "service",
                    "total" : 3,
                    "count" : 1,
                    "value" : 3
            },
            {
                    "_id" : "Quality",
                    "total" : 2,
                    "count" : 1,
                    "value" : 2
            },
            {
                    "_id" : "Price",
                    "total" : 1,
                    "count" : 1,
                    "value" : 1
            }
    ],
    "ok" : 1
}

The model refers to the correct collection.

Thank:)

+4
source share
1 answer

Your item.idin function $matchis a string, so you will need to convert it to an ObjectID , for example:

$match: { item: mongoose.Types.ObjectId(item.id) }

GitHub aggregate .

+4

Source: https://habr.com/ru/post/1589401/


All Articles