【问题标题】:Node JS preventin users from deleting other user's productsNode JS 防止用户删除其他用户的产品
【发布时间】:2020-09-18 06:34:58
【问题描述】:

我有一个使用 Node JS 构建的 REST API,我目前使用 MongoDB 作为我的数据库。我想防止用户删除其他用户的产品,为此我检查了解码令牌中的 userId 是否与产品 userId 相同。

产品架构

const mongoose = require("mongoose");

const productSchema = mongoose.Schema(
  {
    _id: mongoose.Schema.Types.ObjectId,
    userId: mongoose.Schema.Types.ObjectId,
    name: { type: String, required: true },
    price: { type: Number, required: true },
    productImage: { type: String, required: false },
    category: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Category",
      required: true
    },
    gender: { type: String, required: true }
  },
  { timestamps: { createdAt: "created_at" } }
);

module.exports = mongoose.model("Product", productSchema);

删除产品方法:

  const id = req.params.productId;
  Product.findById({ _id: id }).then((product) => {
    if (product.userId != req.user._id) {
      return res.status(401).json("Not authorized");
    } else {
      Product.deleteOne({ _id: id })
        .exec()
        .then(() => {
          return res.status(200).json({
            message: "Product deleted succesfully",
          });
        })
        .catch((err) => {
          console.log(err);
          return res.status(500).json({
            error: err,
          });
        });
    }
  });
};

正如你们首先看到的,我正在搜索执行 findByID 方法以访问产品的 userId 属性,然后我将响应中的 userId 与解码令牌中的 userId 进行比较。

我认为我的方法效率不高,因为它同时运行 findById 和 deleteOne 方法。

您能帮我找到更好的解决方案吗?

【问题讨论】:

  • 这是一件好事,因为您可能希望通知您的用户他们尝试删除的产品不存在,但是您始终可以在 deleteOne 方法中同时指定 userId 和 productId。
  • 一个findById 和一个deleteOne 也不是低效的。你在做毫无意义的微优化。

标签: javascript node.js mongodb api mongoose


【解决方案1】:

正如 Guy Incognito 所说,您尝试做的事情是好的,您可能希望保持这种状态,以防您发送 404 状态,说明他们尝试删除的产品不存在。

但是,如果您尝试只使用一个请求来完成此操作

Product.deleteOne({ _id: id, userId: req.user._id })

希望对你有帮助!

【讨论】:

  • 嘿,非常感谢你和 Incognito 的家伙,它成功了 :)
  • 嘿@typicallearner 和@Guy Incognito。我像你说的那样更新了我的方法,像这样:exports.deleteProduct = (req, res) => { const id = req.params.productId; Product.deleteOne({ _id: id, userId: req.user._id }, (err, result) => { if (err) { return res.status(401).json("Not authorized"); } return res.status(200).json("Product deleted"); }); };,但我总是得到状态 200,并且产品没有被删除。我认为它正在发生,因为我发送给删除一个回调函数的 err 参数为空。知道如何解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-29
  • 1970-01-01
  • 2021-12-08
  • 2016-07-05
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多