Meteor-Community-Packages / meteor-schema-index

Control some MongoDB indexing with schema options
MIT License
38 stars 17 forks source link

Unique: true is not working or not returning any validation error #13

Closed ZhuQinglei closed 6 years ago

ZhuQinglei commented 7 years ago

@aldeed I am having problem to get the notUnique error at all. Here is my code for schema (the collection is placed in imports folder and imported to client and server side respectively, so both client and server shares the same collection schema code):

Organizations.schema = new SimpleSchema({
organization_name: {
        type: String,
        label: 'Organization Name',
        unique: true,  // not giving validation error
        index: true,
        sparse: true,
        custom(){  // this is not working as well
// Since it's not from server side checking function, I believe we dont have to use tracker, right??
          if (Meteor.isClient && this.isSet) {
                let exist = Organizations.findOne({organization_name: this.value});
                console.log(exist);
                if (exist) {
                    this.validationContext.addValidationErrors([{
                        name: 'organization_name',
                        type: 'notUnique',
                        value: this.value,
                        message: 'Organization Name is already taken, please use a different name',
                    }]);
                    console.log(this.validationContext);
                }
                return false;
            }
        },
        min: 1,
        max: 50,
    },

.....
}, {tracker: Tracker});

Here is my code for mapping error message for displaying on client side:

 let validateContext = Organizations.schema.namedContext('createNewOrganization');

        validateContext.validate(currentState);

        // get errors
        let invalidKeys = validateContext.validationErrors();

        invalidKeys = _.map(invalidKeys, function (o) { // get error messages
            return _.extend({message: validateContext.keyErrorMessage(o.name)}, o);
        });

and I can find the document with the same name as shown below, so it should add the error to the current context. screen shot 2017-05-12 at 1 46 55 pm

But I did not see the unique error in my validation errors as there are only 5 errors without the expected notUnique error: screen shot 2017-05-12 at 1 58 35 pm

So it is not displayed on the screen as well, where all the other error messages are correct: screen shot 2017-05-12 at 1 46 41 pm

Do you know why it is behaving like this?

aldeed commented 7 years ago

There is no obvious issue here. Please create a minimal reproduction app and post a link to the repo if you still need help with this.

SimonSimCity commented 6 years ago

Have you had the index on this property for long and now just changed the unique boolean? See #19 for details.