'Validation not working mongoose

Im using Monggose 4.8.1. I have a simple schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var Organisation = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Organisation name must be provided'],
    unique: [true, 'Organisation name must be unique']
  },
  createdBy: { 
    type: String, 
    ref: 'User'
  },
  createdOn: {
    type: Date,
    "default": Date.now
  },
  availableUntil: {
    type: Date
  }
});

mongoose.model('Organisation', Organisation);

I've already saved the email [email protected] in the document.

Now I want to try saving it again and first check that its valid using validateAsync. So i expect to get an error because the email is not unique.

var organisation = new Organisation({
    name: '[email protected]'
});

var validResult = organisation.validateSync();

console.log('validResult is ', validResult);

But validResult is always undefined...

EDIT

I added an extra attribute to my schema:

  eggs: {
    type: Number,
    min: [6, 'Too few eggs'],
    max: 12
  }

And then tried to save eggs: 3 and this produced an error. So bizarrely, mongoose validation does not seem to check if a value is unique or not, even when set in the schema...



Solution 1:[1]

Mark.

Could you verify that mongodb has record for your saved model: db.organisations.find()?

it looks like if you have undefined value it means the document had passed validation steps by following the documentation for validateSync():

  var err = doc.validateSync();
  if ( err ){
    handleError( err );
  } else {
    // validation passed
  }

Solution 2:[2]

For this type of validation you can follow this process using path and validate.

in schema

var OrganisationSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Organisation name must be provided']
  }
 //....
});


OrganisationSchema.path('name').validate(function(value, done){
  var self = this;
  if(!self.isNew){
    return done(true);
  }else{
   //mongoose.models['Organisation'] or self.model('Organisation')
    mongoose.models['Organisation'].count({name: value}, function(err, count){
      if(err){
        return done(err);
      }

      return done(!count)
    });
  }
}, "This email already exists" );


mongoose.model('Organisation', OrganisationSchema);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 oivoodoo
Solution 2