admin管理员组

文章数量:1389903

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...

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...

Share Improve this question edited Feb 7, 2017 at 10:51 Mark asked Feb 7, 2017 at 10:29 MarkMark 5,10817 gold badges67 silver badges125 bronze badges 1
  • 1 any update on this? i notice validateSync doesn't work with a few type validations nor does it work with custom validators – Darbs Commented Apr 22, 2017 at 18:02
Add a ment  | 

3 Answers 3

Reset to default 1

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);

Mark.

Could you verify that mongodb has record for your saved model: dbanisations.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
  }

Please check your mongodb connection string does contain the database name. Also , you can check your mongodb database as well . If it is using "test" named collection then drop that collection and let it create new one. This resolved issue for me . Thanks

本文标签: javascriptValidation not working mongooseStack Overflow