2

I don't think this is a duplicate, but please correct me if I'm wrong. Anyway, I would like to return only "apple" and the customer member role that matches the user's object email address. I am using $elemMatch, but that returns the whole customer object, I only want the "member" property, that's it.

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "orange" : "yes",
    "customers" : [ 
        {
            "name" : "Jay Smith",
            "email" : "[email protected]",
            "member" : "silver", 
        },
        {
            "name" : "Sarah Carter",
            "email" : "[email protected]",
            "member" : "gold",
        },
        {
            "name" : "Jack Whatever",
            "email" : "[email protected]",
            "member" : "gold",
        },
    ]
 }

Ideal result back would be:

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "member" : "gold"
}

or even this would suffice:

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "orange" : "yes",
    "customers" : [
         {"member" : "gold"}
    ]
}

This is currently what I have:

   ItemsModel.find({ _id: { $in: _.pluck(user.items, 'itemId') }, active: true},
       {apple: 1, customers: {$elemMatch: {email: user.email}} }, 
           function(error, items) {
               if (error) { return next(error); }

                req.payload = {};
                req.payload.items = items;
                next();
            });

Any help would be really appreciated. Is this even possible? Thanks!

1 Answer 1

4
ItemsModel.aggregate([
  { $unwind: '$customers' },
  { $match: { _id: { $in: _.pluck(user.items, 'itemId'), 'customers.email': user.email } },
  { $project : { _id:1 , apple:1, member:'$customers.member' }}
], function(err, res){
  // rest of your code here
})

Will give you

{
    "_id" : ObjectId("54d24e5df2878d40192beabd"),
    "apple" : "yes",
    "member" : "gold"
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting it as customers: ["member": "gold"], not as "member": "gold", but I'll still mark this as the correct answer. Genius stuff. Thank you!
Oops, should be member:'$customers.member'. I've modified my answer

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.