Validate object against Mongoose schema without saving as a new document

Justin picture Justin · Jan 31, 2016 · Viewed 12.5k times · Source

I'm trying to validate some data that will be inserted into a new document, but not before a lot of other things need to happen. So I was going to add a function to the static methods that would hopefully validate objects in an array against he model schema.

Heres the code thus far:

module.exports = Mongoose => {
    const Schema = Mongoose.Schema

    const peopleSchema = new Schema({
        name: {
            type: Schema.Types.String,
            required: true,
            minlength: 3,
            maxlength: 25
        },
        age: Schema.Types.Number
    })

    /**
     * Validate the settings of an array of people
     *
     * @param   {array}     people  Array of people (objects)
     * @return  {boolean}
     */
    peopleSchema.statics.validatePeople = function( people ) {
        return _.every(people, p => {
            /**
             * How can I validate the object `p` against the peopleSchema
             */
        })
    }

    return Mongoose.model( 'People', peopleSchema )
}

So the peopleSchema.statics.validatePeople is where I'm trying to do the validation. I have read through mongooses validation documents, but it doesn't state how to validate against a model without saving the data.

Is this possible?

Update

One of the answers on here pointed me towards the proper validation method, which seems to work, but now its throwing an Unhandled rejection ValidationError.

Heres the static method used to validate data (without inserting it)

peopleSchema.statics.testValidate = function( person ) {
    return new Promise( ( res, rej ) => {
        const personObj = new this( person )

        // FYI - Wrapping the personObj.validate() in a try/catch does NOT suppress the error
        personObj.validate( err => {
            if ( err ) return rej( err )

            res( 'SUCCESS' )
        } )
    })
}

Then heres me testing it out:

People.testValidate( { /* Data */ } )
    .then(data => {
        console.log('OK!', data)
    })
    .catch( err => {
        console.error('FAILED:',err)
    })
    .finally(() => Mongoose.connection.close())

Testing it out with data that doesnt follow the schema rules will throw the error, and as you can see, I try to catch it, but it doesnt seem to work.

P.S. Im using Bluebird for my promises

Answer

zangw picture zangw · Jan 31, 2016

There is one way to do that through Custom validators. When the validation failed, failed to save document into DB.

var peopleSchema = new mongoose.Schema({
        name: String,
        age: Number
    });
var People = mongoose.model('People', peopleSchema);

peopleSchema.path('name').validate(function(n) {
    return !!n && n.length >= 3 && n.length < 25;
}, 'Invalid Name');

function savePeople() {
    var p = new People({
        name: 'you',
        age: 3
    });

    p.save(function(err){
        if (err) {
             console.log(err);           
         }
        else
            console.log('save people successfully.');
    });
}

Or another way to do that through validate() with same schema as you defined.

var p = new People({
    name: 'you',
    age: 3
});

p.validate(function(err) {
    if (err)
        console.log(err);
    else
        console.log('pass validate');
});