THpubs
THpubs

Reputation: 8162

Can't set a field to be unique in a Meteor Collection

I'm trying to set one field to be unique using simple schema. But no matter what I do it's not working. Here's how I set it up :

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();
      }
    }
  },
});

I even tried to reset meteor. If I add a duplicate value, it won't add the record but won't even give any errors when validating.

Upvotes: 0

Views: 775

Answers (1)

Faisal Hasnain
Faisal Hasnain

Reputation: 485

There is no built in validation for unique fields in simple schema. You have to use custom simple schema validation as mentioned in the 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"
          }]);
        }
      });
    }
  }
}

This will give invoke custom validation using validation context.

Note: This will be asynchronous as it has to query the database on server side to check whether the field contains unique data item or not.

Upvotes: 0

Related Questions