2015-07-10 74 views
1

我在Mongoose中有一個Article模型,其中有幾個屬性,其中之一是布爾值approved如果正在更改某個屬性,請不要更改updated_at屬性

我也有兩個日期屬性,created_atupdated_at。我使用下面的函數處理這兩個:

ArticleSchema.pre('save', function (next) { 
    'use strict'; 
    var now = new Date(); 
    this.updated_at = now; 
    if (!this.created_at) { 
     this.created_at = now; 
    } 
    next(); 
}); 

使用此代碼,updated_at即使我只批准物品被改變 - 不過,我使用的是updated_at屬性顯示一個微小的「編輯」文字,如果updated_at !== created_at

如果有任何屬性BUT approved正在改變,有沒有辦法可以改變updated_at

謝謝!

回答

3

您可以使用Document#modifiedPaths() method列出所有變更路徑:

ArticleSchema.method('isUpdated', function() { 
    'use strict'; 
    var modified = this.modifiedPaths(); 
    switch (modified.length) { 
     case 0: 
      return false; 
     case 1: 
      return !~modified.indexOf('approved'); 
     default: 
      return true; 
    } 
}); 

ArticleSchema.pre('save', function (next) { 
    'use strict'; 
    var now = new Date(); 
    if (!this.created_at) { 
     this.created_at = this.updated_at = now; 
    } else if (this.isUpdated()) { 
     this.updated_at = now; 
    } 
    next(); 
});