Im trying to return a list of ratings from a given user, filtered by category.
var UserSchema = new Schema({
...
ratings: [{
item: { type: Schema.Types.ObjectId, ref: 'Items' },
category: String,
rating: Number
}]
If I do the following, I only get the first rating for that category:
var query = User.findOne(userId, 'ratings');
query.select({ 'ratings': { $elemMatch: { 'category': req.query.category }}});
The following also returns only the first rating:
var query = User.find();
query.where({'_id': userId, 'ratings.category': req.query.category});
query.select({ 'ratings.$': 1 });
I was able to aggregate the correct results with the following, however, I dont think that'll work since I cant populate after an aggregation.
var query = User.aggregate(
{ $match: { _id: userId }},
{ $project: { _id: 1, ratings: 1 }},
{ $unwind: '$ratings' },
{ $match: { 'ratings.category': req.query.category }}
);