Manuel Di Iorio
Manuel Di Iorio

Reputation: 3761

Validation on user inputs with MongoDB and mongoose?

I would an unified method to validate my schemas assuming a user input, so not only apply the built-in validation on save/update, but also on find(), etc..

var User = mongoose.model("User", new Schema({
    name:   {type: String, minlength: 5, maxlength: 128, required: true, unique: true});
}));

What I want is to run validators every time before I run the queries with mongoose, to assure that the user inputs comply with the global schema rules.

Something like that in my route:

var username = $.get["username"], //An input from GET querystring

User = mongoose.model("User");

User.validate({name: username}, function(err) {
    if (err) return console.log("not valid input"); //i.e. too short

    //run query if valid
});

Is there a plugin (assumed that I'm not using Express) or maybe other already included in mongoose for that?

Upvotes: 0

Views: 3352

Answers (1)

Yerken
Yerken

Reputation: 1942

Documentation: http://mongoosejs.com/docs/validation.html It is supported in mongoose by default. If you are looking for generic validation before each save operation you can specify the field to be validated path and the validation validate(function(valueEntered, howToRespond). If the validation is not passed the error will be thrown as shown in the example below.

Example: Using bluebird for sake of convenience. The following snippet validates the email, before every save operation.

var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var Schema = mongoose.Schema;
var UserSchema = new Schema({
  name: String,
  email: {
    type: String,
    lowercase: true
  },
  password: String,
});

UserSchema
  .path('email')
  .validate(function(value, respond) {
    var self = this;
    return this.constructor.findOneAsync({ email: value })
      .then(function(user) {
        if (user) {
          if (self.id === user.id) {
            return respond(true);
          }
          return respond(false);
        }
        return respond(true);
      })
      .catch(function(err) {
        throw err;
      });
  }, 'The specified email address is already in use.');

Upvotes: 1

Related Questions