Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating multiple Mongoose schema properties?

I'm trying to do the classic thing of making sure a user's username is not the same as their password, in Nodejs/Mongoose.

I was thinking it'd be good to use a seperate validation function, but I can't work out how to do it.

So far I've used the model code from Alex Young's Notepad tutorial. He creates a virtual password property which I've re-used.

I've got basic validation as follows:

function validatePresenceOf(value) {
    return value && value.length;
}

User = new Schema({
    'username': {
        type: String,
        validate: [
            validatePresenceOf, 'a username is required',
        ],
        index: { unique: true }
    },
});

How would I allow a validator to access other properties?

like image 781
benui Avatar asked Sep 10 '11 02:09

benui


People also ask

Is Mongoose validation customizable?

If an error occurs, your Model#save callback receives it. Validation is customizable.

What is validate in Mongoose schema?

Validation is defined in the Schema. Validation occurs when a document attempts to be saved, after defaults have been applied. Mongoose doesn't care about complex error message construction. Errors have type identifiers.

What does $Set do in Mongoose?

The $set operator replaces the value of a field with the specified value. The $set operator expression has the following form: { $set: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.

Does Mongoose actually validate the existence of an object ID?

No, an ObjectId field that's defined in your schema as a reference to another collection is not checked as existing in the referenced collection on a save.


1 Answers

You can call additional properties of the schema via this.propertyToBeCalled.

schema.path('name').validate(function(v) {
    if (v === this.password) {
        return false;
    } else {
        return true;
    }
}, 'my error type');

Or something like that anyway.

like image 84
Logos Avatar answered Oct 04 '22 05:10

Logos