无法从阵列中提取记录

时间:2019-01-25 10:12:50

标签: node.js mongoose

我正在尝试使用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." });
  });
};

1 个答案:

答案 0 :(得分:1)

我不确定您是否正确使用拉力,请查看此链接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." });
  });
};