0

I'm trying to exclude an object in an array from the results when using find in Mongoose with MongoDB.

Query:

Model.findOne({
    'eventid': query
    }
    , { 
    'email': 0, 
   'guests.$.email': 0 
    }, function (err, result) {
    if (err) throw err;
    if (result) {
        console.log(result);
    } else {
        res.send(JSON.stringify({
            error: 'Error'
        }))
    }
})

Excluding the 'email' field with 'email': 0 works fine. However, 'guests' is an array with multiple objects and I want to remove the email field from the results. I get the following error:

MongoError: Cannot exclude array elements with the positional operator.

Apparently the position operator $ can only be used from including elements in the array, not to remove them. What would be the best way to hide the email field in the 'guests' array.

Example dataset:

{ _id: 5b71c9af75a8e95dc33e7eef,
eventid: 'ALRW9by',
email: '[email protected]',
guests:
 [ { _id: 5b72f16ea61d2911d806daa8 },
   { _id: 5b7306b605bf17131f80fd0a,
     userid: 'CuzcO3c',
     naam: 'John',
     email: '[email protected]' },
   { _id: 5b7306c705bf17131f80fd0b,
     userid: 'xA7A65U',
     naam: 'Ellen',
     email: '[email protected]' }
   ] }
1

1 Answer 1

2

Just use the dot notation guests.email to exclude the nested fields:

Model.findOne({
    'eventid': query
    }
    , { 
    'email': 0, 
    'guests.email': 0 
    }, function (err, result) {
    if (err) throw err;
    if (result) {
        console.log(result);
    } else {
        res.send(JSON.stringify({
            error: 'Error'
        }))
    }
})
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.