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'); every time
userschemaaccessed in way,userschema.path('email').validatealso fires , validates email string. validation have been done inuserschemaobject, except have been messy.in
.validate(function(value, next)...,valueemail string, ,nextgiven nothing , undefined. (right?)if so, don't see how
return next(false)ornext(!user)can work.i'm familiar
nextin other situations,nextdoing 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:
- yes, function validates email path.
- yes,
valueemail, use better variable naming , callemailinstead ofvalue;nextthat: function says "continue next step." - see comments in code above. but, tldr: if user email exists,
!userfalse; if user doesn't exist,!usertrue. ifnextpassed false-y value, thinks there's error. truth-y value means okay. 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
Post a Comment