3

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

1 Answer 1

3

You could do the population after your aggregation, something like this:

var pipeline = [
  { $match: { _id: userId }},
  { $project: { _id: 1, ratings: 1 }},
  { $unwind: '$ratings' },
  { $match: { 'ratings.category': req.query.category } }
];

User.aggregate(pipeline, function (err, result){
    User.populate(result, {path: "ratings.item"}, callback);  
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.