【发布时间】: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