如果正在更改某个属性,请不要更改updated_at属性
我在Mongoose中有一个Article
模型,有几个属性,其中一个是布尔型的, approved
。
我也有两个date属性created_at
和updated_at
。 我正在处理这两个使用以下function:
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 !== created_at
,我正在使用updated_at
属性来显示一个小的“已编辑”文本。
有没有办法我可以得到updated_at
改变,如果任何属性,但approved
正在改变?
谢谢!
您可以使用Document#modifiedPaths()
方法列出所有修改的path:
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(); });