Jose
Jose

Reputation: 5200

Check for existing user using Mongoose

I'm trying to write a middleware function that (when a POST request is made with a username/password) checks to see if the user being created already exists in the database. I don't know if I'm doing this properly though.

User.find({ username: req.body.username }) returns an object which contains (or does not contain) the user if it exists...but how to properly return to exit if a user under the same username is found? Whenever I test this with Mocha, res.body.msg comes up as 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 with this username already exists' });
  });
  next();
};

User Schema:

var userSchema = new mongoose.Schema({
  username: String,
  authentication: {
    email: String,
    password: String
  }
});

Upvotes: 1

Views: 878

Answers (2)

Alok Deshwal
Alok Deshwal

Reputation: 1126

give it a try very initial create a function to get the user response

function findUser(arg, callback) {
  /* write your query here */
  return callback(pass response here)
}

And then use it where you want

findUser(arg,function(callbackResponse) { /*do something*/ })

Upvotes: 1

Ruben Marrero
Ruben Marrero

Reputation: 1392

Since nodejs is asynchronous, chances are that the response is being sent after you are trying to read it. Make sure to keep the reading process waiting untill response is sent. I personaly use passport for handling that.

Upvotes: 0

Related Questions