【问题标题】:find if product exists and if so, check if user exists in product array of objects查找产品是否存在,如果存在,检查用户是否存在于产品对象数组中
【发布时间】:2019-01-13 02:04:44
【问题描述】:

当用户单击按钮时,他们的 userId 和产品 ID 会发送到我下面的查询。我想检查该产品是否存在,如果存在,则检查同一文档中的对象数组中是否存在特定的 userId。我已经尝试了以下方法,但是当我使用其他产品进行测试时,数组中不存在 userId,它告诉我用户存在。因此,它似乎在检查所有产品,而不仅仅是我传递产品 ID 的产品。

Product.findById(productId).then(product => {
  if (!product) {
    console.log("no product found");
  }
  return Product.find({ "requests.userId": userId })
    .then(result => {
      if (result === undefined || result.length == 0) {
        res.status(200).json({ message: "You can add it!" });
      } else {
        res.status(200).json({ message: "You cannot add this again!" });
      }
    })
    .catch(err => {
      console.log(err);
    });
  });      
});

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    你需要做的是找到同时满足2个条件的产品:

    1. 有一个特定的ID
    2. requests 数组字段中有一个特定的字符串

    您的查询所做的是分别测试这 2 个条件。首先,您找到产品,然后测试是否有满足条件 2 的任何产品。

    要将这两个条件应用于同一产品,请使用单个查询:

    Product.find({ _id: productId, 'requests.userId': userId })
      .then(product => {
        if (product) {
          const [result] = product; // take the first matched item
          // ... do stuff with result
        }
      })
    

    或者,您可以在内存中完成所有这些操作:

     Product.findById(productId).then(product => {
        if (!product) {
          console.log("no product found");
          // ... potentially send an error here
          return;
        } 
    
        // find a match in memory
        const [result] = product.requests.filter(uid => uid === userId);
        if (result) {
          // ...
        }
      });
    

    【讨论】:

    • 非常感谢。我编辑了我的原始问题(不确定你是否能看到它,说它需要审查?)无论如何,我发布了它,所以你可以告诉我是否可以。如果您看不到编辑,请告诉我,我会在评论中发布代码
    • 很高兴为您提供帮助 :)。性能方面,第一个例子应该更好。我不得不拒绝你的编辑,因为你用问题说明编辑了我的答案,而不是问题:)
    • 啊好吧。我懂了。不确定它是否适合这里,但我只是想检查一下是否可以:Product.find({ _id: productId, "requests.userId": userId }) .then(product => { if (!product === undefined || !product.length == 0) { res.status(200).json({ message: "You cannot add this again!" }); console.log(product); } else { res.status(200).json({ message: "go ahead!" }); console.log(product); } }) .catch(err => { console.log(err); });
    • 太棒了!再次感谢,你是救生员:)
    【解决方案2】:

    首先,Ln 4,您正在尝试从 Mongo 模式检查完整产品对象中的用户 ID。

    如果您的 userId 存储在每个单独的产品中, 然后将 Ln 4, Product 更改为 product。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 2014-11-14
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多