Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I want to verify some data that will be embedded in a new document but not before as many other things need to occur. So I was thinking to add a function to the static methods that would hopefully validate objects in an array against the model schema.

Here is the code:

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 attempting to do the validation. I have gone through mongooses validation documents, but it doesn't seem to state how to authenticate against a model without saving the data.

1 Answer

0 votes
by (108k points)
edited by

One way is to perform that with the help of custom validators. When the validation declined, it failed to save the document into the database.

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() function provided by MongoDB with the same schema as you defined.

To help you gain a better understanding, here is a Full Stack Developer Certification Course provided by Intellipaat.

var p = new People({

    name: 'you',

    age: 3

});

p.validate(function(err) {

    if (err)

        console.log(err);

    else

        console.log('pass validate');

});

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

Browse Categories

...