将猫鼬模式字段设为只读

舒尔茨

我有一个猫鼬的“用户”架构,并且其中一个字段需要为只读。(“帐户”字段可以在外部进行更新,因此我不希望对用户的更新覆盖所做的更改。)

var UserSchema = new Schema({
firstName: {
    type: String,
    trim: true,
    default: '',
    validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
    type: String,
    trim: true,
    default: '',
    validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
    type: String,
    trim: true
},
email: {
    type: String,
    trim: true,
    default: '',
    validate: [validateLocalStrategyProperty, 'Please fill in your email'],
    match: [/.+\@.+\..+/, 'Please fill a valid email address']
},
username: {
    type: String,
    unique: 'Username already exists',
    required: 'Please fill in a username',
    trim: true
},
password: {
    type: String,
},
accounts: [{
        account_hash: {type: String},
        account_name: {type: String}        
    }],

updated: {
    type: Date
},
created: {
    type: Date,
    default: Date.now
}
}

我已经看到建议将字段虚拟化的答案,但是保存后,该字段将从Mongo中删除。有没有一种简单的方法可以使Mongoose模式中的特定字段为只读?

阿克里翁

在我看来,最好的办法是在pre 中间件save/update

您可以检查是否更改不希望更改的字段isModified并仅引发关于仅从此处读取字段的错误:

someSchema.pre('save', function(next) { 
  if(this.isModified('someField')) {
    throw 'someField is read only!'
  }
  else {
    next();
  }
});

要进行更新,您应该通过获取更新,this.getUpdate()并在其中查找您的字段。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章