2013-02-16 97 views
1

我想分配預處理器的貓鼬保存事件和加密文件:如何保存之前更改使用前將文檔保存在貓鼬

userShecma.pre('save', function(next) { 
    var self = {}; 
    self.Key = this.password;; 
    self.EncriptedString = encrypt.encrypt(JSON.stringify(this), this.password); 
    self.user = this.user 
    self.decrypt = function() { 
     var user = JSON.parse(encrypt.decrypt(this.EncriptedString, this.Key)); 
     for(var key in user) { 
      this[key] = user[key]; 
     } 
    } 
    for(var key in this){ 
     delete this[key]; 
    } 
    for(var key in self){ 
     this[key] = self[key]; 
    } 
    console.log(this); 
    next(self); 
}); 

我已經嘗試了一堆不同勢的事情,有時我收到一個錯誤,有時它不會更改文檔。

讓我知道如果你需要任何更多的信息,
阿里

編輯:嘗試Benoir的回答,我不能編輯this

回答

1

我想通了: Benoir的答案+您不能添加或刪除文件中屬性/除非它們被定義在Schema中。

+0

您可以使用this.getValue和this.setValue編輯未在Schema中定義的屬性 – 2013-06-01 20:23:33

2

我相信調用next(self)會使下一個處理程序認爲出現錯誤並且不保存文檔。

你應該只調用next()

http://mongoosejs.com/docs/middleware.html 下的「錯誤處理」

+1

不回答問題,問題是如何編輯文檔 – 2013-02-16 21:54:17

+1

您可以通過編輯「this」屬性來編輯文檔。我認爲你這樣做是正確的,但不更新的原因是你將錯誤傳遞給'next',所以它不會保存 – Benoir 2013-02-16 21:55:49