Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

NodeJS and MongooseJS: accessing value from callback in validator

NodeJS and MongooseJS: accessing value from callback in validator

Problem

I'm trying to use validator and express-validator within a NodeJS/ExpressJS/MongoDB/Mongoose app to confirm a user isn't using an Email address that's already been registered. I already have a unique index on the email field, but what I'm trying to do is keep all of my validation in one spot using one method. Thus, my question: validating uniqueness using express-validator.

I've created the schema method to lookup the Email Address, and it's working. I've created the custom validator, and wired it up in the controller. It is also working. My problem is I don't know how to communicate to the validator in the controller the results of the schema method from the callback.

user.js (the model)

...

/**
 * Check for email addresses already in the collection
 */
 checkEmailDupes: function(req, cb) {
   this.model('User').findOne({email: req}, function (err, user) {
     if (err) {
       return cb(err);
     }
     cb(null, user); // this is passing back the expected result
   });
},

...

users.js (the controller)

...
// The call to the custom validator (shown below)
req.assert('email', 'Email must be unique').checkEmailDupes(user);
...

// Check for email addresses that are already registered
expressValidator.Validator.prototype.checkEmailDupes = function(user) {
  user.checkEmailDupes(this.str, function (err, result) {
    if (err) {
      console.log('An error occurred in checkEmailDupes');
    }
    else {
      console.log('Found a user in checkEmailDupes');
      console.log(result); // this is producing the expected result
    }
  });
  return this.error(this.msg || 'Looks like this email address has already been registered');
  return this;
}

I know the return this.error(this.msg...) needs to go elsewhere. Ideally, I'd throw that into the callback, but when I do that I get

TypeError: Object # has no method 'error'

Problem courtesy of: CrankNPlank

Solution

I was ultimately unable to get this method to work. Thanks to @robertklep and his feedback, I decided to use the error code passed back by mongo (in the case of a non-unique value being found for the email, it's MongoError: E11000 duplicate key error index) and set the error message based on that.

It ultimately looks like the following (in the user controller):

user.save(function(err) {
  if (err) {
    // Instantiate the errors array
    var errors = [];

    // Email address already in DB
    if (err.code == 11000) {
      // Build the error object
      var error = {
        param: 'email',
        msg: 'The email address entered has already been registered',
        value: ''
      };

      // Push the error onto the errors array
      errors.push(error);
    }

    return res.render('users/signup', {
      errors: errors,
      user: user
    });
  }

  ...
Solution courtesy of: CrankNPlank

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

NodeJS and MongooseJS: accessing value from callback in validator

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×