node.js - Check for existing user using Mongoose -


i'm trying write middleware function (when post request made username/password) checks see if user being created exists in database. don't know if i'm doing though.

user.find({ username: req.body.username }) returns object contains (or not contain) user if exists...but how return exit if user under same username found? whenever test mocha, res.body.msg comes undefined.

code:

module.exports = exports = function(req, res, next) {   user.find({ username: req.body.username }, (err, user) => {     if (err) return handledberror(err, res);     if (user) return res.status(200).json({ msg: 'an account username exists' });   });   next(); }; 

user schema:

var userschema = new mongoose.schema({   username: string,   authentication: {     email: string,     password: string   } }); 

since nodejs asynchronous, chances response being sent after trying read it. make sure keep reading process waiting untill response sent. personaly use passport handling that.


Comments