【问题标题】:Unable to pull record from array无法从数组中提取记录
【发布时间】:2019-01-25 19:06:02
【问题描述】:

我正在尝试使用 Mongoose 'pull' 从对象数组中删除一个项目。我得到一个 200 的状态码,显然一切都很好,但实际上并没有删除记录? mongo db 中的 userId 如下所示:

userId: ObjectId("6b275260a6g58308e510721b")

exports.putDislike = (req, res, next) => {
  const productId = req.body.productId;
  const userId = req.body.userId;

  Product.findById(productId)
  .then(product => {
    if (!product) {
      return next(new Error('Product not found.'));
    }
     product.requests.pull(userId)
     return product.save()
     .then(result => {
        res.status(200).json({ message: "Item request removed." });
     })
  })
  .catch(err => {
    res.status(500).json({ message: "Removing request failed." });
  });
};

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    我不确定您是否正确使用了 pull,请查看此链接 https://docs.mongodb.com/manual/reference/operator/update/pull/

    据此,我认为您的代码应该类似于下面的示例:

    exports.putDislike = (req, res, next) => {
      const productId = req.body.productId;
      const userId = req.body.userId;
    
      Product.update(
        { "_id": productId },
        { $pull: { requests: {userId: userId} } })
      .then(result => {
          res.status(200).json({ message: "Item request removed." });
      })
      .catch(err => {
        res.status(500).json({ message: "Removing request failed." });
      });
    };
    

    【讨论】:

    • 谢谢你,会试试看。我在文档中看到了这一点 doc.subdocs.pull(4815162342); mongoosejs.com/docs/api.html#model_Model.updateOne
    • 不得不稍微改变你的代码,但让它工作。这个:{ $pull: { requests: userId } }) 需要是 { $pull: { requests: {userId: userId} } }
    猜你喜欢
    • 2021-12-11
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2018-04-08
    相关资源
    最近更新 更多