猫鼬从结果中排除数组中的对象

时间:2018-08-28 16:25:01

标签: javascript arrays mongodb mongoose

当试图在MongoDB中使用Mongoose中的find时,我试图从结果中排除数组中的对象。

查询:

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

'email'排除'email': 0字段是可以的。但是,'guests'是一个包含多个对象的数组,我想从结果中删除电子邮件字段。我收到以下错误:

  

MongoError:无法使用位置运算符排除数组元素。

显然,只能将位置运算符$用于数组中的元素,而不能删除它们。在'guests'数组中隐藏电子邮件字段的最佳方法是什么。

示例数据集:

{ _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' }
   ] }

1 个答案:

答案 0 :(得分:0)

只需使用点符号guests.email即可排除嵌套字段:

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'
        }))
    }
})
相关问题