Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose aggregate returning empty result [duplicate]

I have problems with a mongoose aggregate request.

It's kind of driving me crazy cause I can't find a solution anywhere. I would be very grateful for any support.

The schema:

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'm using an aggregation to compute the sum of evaluations for each criterion for a given item.

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);
});

Result is always empty....

I'm logging all queries that 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 is referencing the correct collection.

Thank you :)

like image 673
yosrO Avatar asked Dec 06 '22 21:12

yosrO


1 Answers

Your item.id in the $match function is a String, therefore you will need to convert it to an ObjectID, like so:

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

You can refer to this issue on GitHub aggregate for more details.

like image 114
syang13 Avatar answered Jan 01 '23 03:01

syang13