【问题标题】:mongoose, how to correctly remove reference with middleware?猫鼬,如何正确删除中间件的引用?
【发布时间】:2017-03-26 06:22:46
【问题描述】:

有人可以帮我做猫鼬手术吗?我目前正在构建这个投票系统。 我有这个Poll 模型:

var Poll = new Schema({
    title: {
        type: String,
        required: true
    },
    options: [{text:String, count: {type: Number, default: 0}}],
    author: {
        type: Schema.ObjectId,
        ref: 'Account',
    },
    disabled: {
        type:Boolean,
        default: false,
    },
    date: {type: Date, defalut: Date.now},
});

我有这个 Log 模型:

var Log = new Schema({
    ip: String,
    voter: {
        type: Schema.ObjectId,
        ref: 'Account'
    },
    poll: {
        type: Schema.ObjectId,
        ref: 'Poll'
    },
    date: {type: Date, defalut: Date.now},
 });

每次用户投票时,日志都会创建如下内容:

{ ip: '::1',
  voter: 5824e7c3b6e659459818004f,
  poll: 58264b48f767f2270452b5cb,
  _id: 58264b4cf767f2270452b5ce }

现在如果用户删除他的一项投票,例如 58264b48f767f2270452b5cb,我还想删除所有具有相同投票 ID 的日志文档。

我阅读了一些其他答案,并提出了一个中间件

Poll.pre('remove', function(next){
  var err = new Error('something went wrong');
  this.model('Log').remove({poll: this._id}, function(err){
    if (err) throw err;
  })

  next(err);
});

但它根本不起作用。

我该怎么办?谢谢。

【问题讨论】:

    标签: node.js mongodb mongoose model ref


    【解决方案1】:

    在当前状态下,Model.remove() 调用不使用钩子,为什么?因为调用时内存中不存在文档,所以需要先查询 mongo,然后删除 doc 以确保 hook 可以正常工作。

    有一个 CR 用于添加此行为,但尚未实现。

    所以目前的方法是使用类似的方法:

    myDoc.remove();
    

    举个例子,这是行不通的:

    var myAccount = new Account({
      name: "jim"
    })
    var myPoll = new Poll({
      question: "You like stuff?"
    })
    var myLog = new Log({
      voter: myAccount,
      poll: myPoll
    })
    
    myAccount.save()
    .then(myPoll.save())
    .then(myLog.save())
    .then(Poll.remove({
      question: "You like stuff?"
    }, function(err) {
      console.log(err)
    }))
    

    这将起作用:

    myAccount.save()
    .then(myPoll.save())
    .then(myLog.save())
    .then(myPoll.remove(function(err) {
      console.log(err)
    }))
    

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2021-11-21
      • 2019-02-22
      • 2021-07-08
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 2021-09-27
      • 2021-07-28
      相关资源
      最近更新 更多