mongodb - Mongoose - 确保只有对象的创建者可以删除它
问题描述
我有一个模式,在其他字段中有一个指示创建它的用户,称为 project_manager。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const idValidator = require('mongoose-id-validator');
(...)
let ProjetoSchema = new Schema({
name : {
type : String,
required : true
},
goal : {
type : String,
required : true
},
activity : {
type : AtividadeSchema,
required : true
},
date : {
type: Date,
default: Date.now
},
// Teacher that initiates the activity
project_manager : {
type : mongoose.Schema.Types.ObjectId,
ref : 'User',
required : true
},
// Teachers invited to collaborate
teachers : {
type : [mongoose.Schema.Types.ObjectId],
ref : 'User',
}
});
ProjetoSchema.plugin(idValidator);
module.exports = mongoose.model('Projeto', ProjetoSchema);
我试图确保只有 project_manager 可以删除给定的 Projeto,但是我无法做到这一点。
function remove(req, res) {
let query = {
_id : req.params.id
};
Projeto.findByIdAndRemove(query)
.then(projeto => {
if(!projeto) {
return res.status(404).json({error: 'not_found', message: 'This project doesn\'t exist.'});
}
if(projeto.project_manager.toString() != req.user._id.toString()) {
return res.status(403).json({error: 'forbidden', message: 'You can\'t delete this project.'});
}
res.status(200).send("Project deleted.");
})
.catch(utils.handleError(req, res));
如果我尝试使用其他用户删除它,则会显示该用户不是 project_manager 的错误消息,但该对象仍被删除。
如何确保只有 project_manager 可以删除它?
解决方案
findByIdAndRemove
在验证所有权之前不要使用?
function remove(req, res) {
let query = {
_id : req.params.id
};
Projeto.findById(query)
.then(async (projeto) => {
if(!projeto) {
return res.status(404).json({error: 'not_found', message: 'This project doesn\'t exist.'});
}
if(projeto.project_manager.toString() != req.user._id.toString()) {
return res.status(403).json({error: 'forbidden', message: 'You can\'t delete this project.'});
} else {
await Project.findByIdAndRemove(query);
}
res.status(200).send("Project deleted.");
})
.catch(utils.handleError(req, res));
推荐阅读
- java - Servlet 加载属性文件
- c++ - 错误:g++:错误:main.o:没有这样的文件或目录
- linux - 使用 awk 命令将 2 个文件与算术进行比较
- php - php用数据库上的另一列序列化数据
- r - 如何找到 H2O 模型版本
- javascript - 定位和样式化 SVG tspan?
- javascript - 创建标签后Chrome扩展回调函数不起作用
- javascript - 加载页面时,我可以在 HTML、javascript 或 CSS 中初始化缩放以设置为 100%
- database - 使用VB.Net将数据从datagridview发送到水晶报表
- javascript - 如何获得对象数组中多个数组的总和?