2016-11-11 90 views
1

有人可以幫我做一個貓鼬手術嗎?我目前正在建立這個投票系統。 我有這個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}, 
}); 

,我有這個登錄模型:

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

,但它不工作。

我該怎麼辦?謝謝。

回答

0

在當前狀態下Model.remove()調用不使用掛鉤,爲什麼?由於文檔在調用時無法在內存中顯示,因此需要先查詢mongo,然後刪除文檔以確保鉤子能正常工作。

有一個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) 
}))