简体   繁体   中英

Mongoose exclude object in array from results

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: 'test@gmail.com',
guests:
 [ { _id: 5b72f16ea61d2911d806daa8 },
   { _id: 5b7306b605bf17131f80fd0a,
     userid: 'CuzcO3c',
     naam: 'John',
     email: 'test2@gmail.com' },
   { _id: 5b7306c705bf17131f80fd0b,
     userid: 'xA7A65U',
     naam: 'Ellen',
     email: 'test3@gmail.com' }
   ] }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM