Meteor simpleSchema 阻止字段更新

Meteor simpleSchema prevent field updates

是否可以使用模式本身指定字段不可更新,而不是在 allow/deny 规则中定义它?

我想知道,因为我使用快速表单允许用户根据用户文档(帐户包)编辑他们的用户详细信息,我想防止他们能够更改他们的电子邮件地址的验证状态。

基于用户角色的规则只允许管理员和 meteor 本身更改此字段的状态。

我希望得到这样的结果:

    emails: {
        type: Array,
        optional: true
    },
    "emails.$": {
        type: Object
    },
    "emails.$.address": {
        type: String,
        regEx: SimpleSchema.RegEx.Email
    },
    "emails.$.verified": {
        type: Boolean
        allowRoles: ['admin','system'] // this does not exist
    },

问候,克里斯

您有几种不同的选择。

要防止任何人更新字段,您可以在标志定义中设置 denyUpdate 字段(需要 aldeed:collection2)

"emails.$.verified": {
    type: Boolean
    denyUpdate: true
},

要允许它仅由管理员更新,您可以尝试使用自定义验证器来检查 userId 以查看它是否是管理员(示例需要 aldeed:collection2 和 alanning:roles)

"emails.$.verified": {
    type: Boolean
    custom: function() {
      if ( this.isSet && this.isUpdate &&  !Roles.userIsInRole(this.userId, "admin") ) {
        return "unauthorized";
      }
    }
},

您可能还想为 "unauthorized" 验证错误定义一条消息。

SimpleSchema.messages({
   "unauthorized" : "You do not have permission to update this field"
})

如果用户尝试更改字段,这将向用户显示错误。

或者,您可以简单地取消设置非管理员用户提供的值,并允许继续进行其余的更新。

"emails.$.verified": {
    type: Boolean
    autoValue: function() {
      if ( !Roles.userIsInRole(this.userId, "admin") ) {
        this.unset();
      }
    }
},