首页 > 解决方案 > 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 可以删除它?

标签: mongodbmongoose

解决方案


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));

推荐阅读