【问题标题】:Can't set a field to be unique in a Meteor Collection无法将字段设置为流星集合中的唯一字段
【发布时间】:2016-09-06 14:03:26
【问题描述】:

我正在尝试使用简单的模式将一个字段设置为唯一的。但无论我做什么,它都不起作用。这是我的设置方式:

let schema = new SimpleSchema({
  name: {
    type: String,
    label: 'Committee name',
    max: 200
  },
  shortName: {
    type: String,
    label: 'Short name',
    max: 10,
    index: true,
    sparse: true,
    unique: true,
    autoValue: (com) => {
      if (com.shortName) {
        return com.shortName.toLowerCase();
      }
    }
  },
});

我什至尝试重置流星。如果我添加重复值,它不会添加记录,但在验证时甚至不会给出任何错误。

【问题讨论】:

  • 您使用的是插入更新还是更新插入?
  • 是的。添加项目我使用insert 但在此之前我使用验证方法得到错误:Collection.simpleSchema().namedContext('insertForm').validate(values)

标签: meteor meteor-collection2 simple-schema


【解决方案1】:

简单模式中的唯一字段没有内置验证。您必须使用official docs 中提到的自定义简单模式验证。

username: {
  type: String,
  regEx: /^[a-z0-9A-Z_]{3,15}$/,
  unique: true,
  custom() {
    if (Meteor.isClient && this.isSet) {
      Meteor.call("accountsIsUsernameAvailable", this.value, (error, result) => {
        if (!result) {
          this.validationContext.addValidationErrors([{
            name: "username",
            type: "notUnique"
          }]);
        }
      });
    }
  }
}

这将使用验证上下文提供调用自定义验证。

注意:这将是异步的,因为它必须在服务器端查询数据库以检查字段是否包含唯一数据项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-20
    • 2017-05-06
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2014-09-01
    相关资源
    最近更新 更多