本文介绍了猫鼬:不允许更新特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var post = mongoose.Schema({
...
_createdOn: Date
});
我只允许在创建文档时设置_createdOn
字段,而不允许在以后的更新中对其进行更改.猫鼬是怎么做的?
I want to allow setting the _createdOn
field only upon document creation, and disallow changing it on future updates. How is it done in Mongoose?
推荐答案
我通过在架构的预保存钩子中设置_createdOn
(仅在第一次保存时)实现了这种效果:
I achieved this effect by setting the _createdOn
in the schema's pre-save hook (only upon first save):
schema.pre('save', function (next) {
if (!this._createdOn) {
this._createdOn = new Date();
}
next();
});
...并禁止在任何其他地方进行更改:
... and disallowing changes from anywhere else:
userSchema.pre('validate', function (next) {
if (this.isModified('_createdOn')) {
this.invalidate('_createdOn');
}
next();
});
这篇关于猫鼬:不允许更新特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!