javascript - How do schema validation functions work in mongoose? -


while working through mean stack tutorial, find myself puzzled following mongoose verification code.

user-service.js

exports.finduser = function(email, next){     user.findone({email:email.tolowercase()}, function(err,user){         next(err, user);     }) }; 

user.js

var userservice = require('../services/user-service');  var userschema = new schema({       ...     email:      {type: string, required: 'please enter email'},     ... });  userschema.path('email')     .validate(function(value,next){         userservice.finduser(value, function(err, user){             if(err){                 console.log(err);                 return next(false);             }             next(!user);         });     }, 'that email in use'); 
  1. every time userschema accessed in way, userschema.path('email').validate also fires , validates email string. validation have been done in userschema object, except have been messy.

  2. in .validate(function(value, next)..., value email string, , next given nothing , undefined. (right?)

  3. if so, don't see how return next(false) or next(!user) can work.

  4. i'm familiar next in other situations, next doing here?

here's how works:

userschema.path('email').validate(function (email, next) {     // user given email     // note how changed `value` `email`     userservice.finduser(email, function (err, user) {         // if there error in finding user         if (err) {             console.log(err)             // call next , pass along false indicate error             return next(false)         }         // otherwise, call next whether or not there user         // `user === null` -> `!user === true`         // `user === { someobject }` -> `!user === false`         return next(!user)     })     // error message }, 'that email in use') 

to go along points:

  1. yes, function validates email path.
  2. yes, value email, use better variable naming , call email instead of value; next that: function says "continue next step."
  3. see comments in code above. but, tldr: if user email exists, !user false; if user doesn't exist, !user true. if next passed false-y value, thinks there's error. truth-y value means okay.
  4. it calls "next" step. example

    app.get('/admin*', function (req, res, next) {     req.status = 'i here!'     next() })  app.get('/admin/users/view', function (req, res, next) {     console.log(req.status)    // ==> 'i here!'     res.render('admin/users/view.jade', { somelocals }) }) 

Comments