【问题标题】:Mongoose select $ne in arrayMongoose 在数组中选择 $ne
【发布时间】:2014-07-18 20:27:58
【问题描述】:

我想知道您将如何查询 where array._id != 'someid'。

这是我为什么需要这样做的一个例子。用户想要更新他们的帐户电子邮件地址。我需要这些是唯一的,因为他们使用它来登录。当他们更新帐户时,我需要确保新电子邮件不存在于另一个帐户中,但如果它已经存在于他们的帐户中,请不要给出错误(他们没有更改他们的电子邮件,只是他们的个人资料中的其他内容)。

以下是我尝试使用的代码。它不会给出任何错误,但它始终返回计数 0,因此即使应该创建错误也不会产生错误。

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
  }]
}

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    对于您现有的查询,您的查询的 customers.emailcustomers._id 部分会针对 customers 的所有元素作为一个组进行评估,因此它不会匹配具有 any的文档> 带有customerID 的元素,不管它的email。但是,您可以使用$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
      }
    });
    

    【讨论】:

    • 这比我想出的要干净得多,我会将其标记为答案。谢谢!
    【解决方案2】:

    我可以使用聚合来做到这一点。

    为什么这没有按照我的方式工作:在查找 $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
          }
        });
    );
    

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 2021-08-16
      • 2015-04-07
      • 2021-01-19
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2020-07-23
      相关资源
      最近更新 更多