Mongoose在数组中select$ ne

我想知道你将如何做一个查询在array._id!='someid'。

这是为什么我需要这样做的一个例子。 用户想要更新他们的帐户电子邮件地址。 我需要这些是唯一的,因为他们使用这个login。 当他们更新帐户,我需要确保新的电子邮件不存在于另一个帐户,但不要提供一个错误,如果它的帐户已经存在(他们没有改变他们的电子邮件,只是在他们的个人资料)。

以下是我尝试使用的代码。 它不会给出任何错误,但它总是返回0的计数,所以即使应该也不会创build错误。

Schemas.Client.count({ _id: client._id, 'customers.email': email, 'customers._id': { $ne: customerID } }, function (err, count) { if (err) { return next(err); } if (count) { // it exists } }); 

我猜它应该使用$ ne或$ not,但是我找不到任何与ObjectId联机的示例。

示例客户端数据:

 { _id: ObjectId, customers: [{ _id: ObjectId, email: String }] } 

使用您现有的查询,您的查询的customers.emailcustomers._id部分将作为一个组在所有customers元素上进行评估,因此无论其email如何,都不会与具有customerID元素的文档相匹配。 但是,您可以使用$elemMatch来更改此行为,以便两个部分一次一个在每个元素上串联操作:

 Schemas.Client.count({ _id: client._id, customers: { $elemMatch: { email: email, _id: { $ne: customerID } } } }, function (err, count) { if (err) { return next(err); } if (count) { // it exists } }); 

我能够使用聚合来做到这一点。

为什么这样做没有按照我的方式工作:当查找$ ne:customerID时,它永远不会返回结果,因为_id确实存在。 它不能结合cutomers.email和customers._id我想要的方式。

以下是它的外观:

 Schemas.Client.aggregate([ { $match: { _id: client._id } }, { $unwind: '$customers' }, { $match: { 'customers._id': { $ne: customerID }, 'customers.email': req.body.email }}, { $group: { _id: '$_id', customers: { $push: '$customers' } }} ], function (err, results) { if (err) { return next(err); } if (results.length && results[0].customers && results[0].customers.length) { // exists } }); );