Title: Validation not working mongoose
Tags: javascript;node.js;mongodb;mongoose
Question: 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 jennagarcia@example.net 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: 'jennagarcia@example.net'
var validResult = organisation.validateSync();
console.log('validResult is ', validResult);
But validResult is always undefined...
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...
Comment: any update on this? i notice validateSync doesn't work with a few type validations nor does it work with custom validators


Here is another answer: 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);

Here is another answer: 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

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:02/07/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><node.js><mongodb><mongoose>', 'Title': 'Validation not working mongoose', 'ViewCount': 8142, 'id': 42087450, 'user_AboutMe': '', 'user_AccountId': 1294821.0, 'user_DisplayName': 'Mark', 'user_Reputation': 4094.0, 'user_Views': 467.0, 'user_id': 1246159.0}}