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?
If an error occurs, your Model#save callback receives it. Validation is customizable.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With