Timo
Timo

Reputation: 261

NodeJS, Mongoose, Express: Check Database if User is New

I am using Mongoose with Express.

I want to check if a username is already taken.

var isNew = function(req, res, next) {
  if (User.find({ 'userData.name': { $exists: false } })) {
    next();
  } else {
    res.redirect('/');
  }
}

my Schema:

var userSchema = mongoose.Schema({
  userData: {
    name: { type: String, required: true, unique: true },
    password: String
  },
  imagePath: { type: String, required: true },
  notes: [ String ],
  contacts: [{
    name: String,
    notes: [ String ]
  }],
  locations: [ String ]
});

Upvotes: 0

Views: 132

Answers (1)

mkhanoyan
mkhanoyan

Reputation: 2079

The below code will work assuming you are passing in json with a name attribute in the request body.

var isNew = function(req, res, next) {
  User.count({ 'userData.name': req.body.name.toLowerCase() }, 
    function (err, count) {
      if (err) {
        return next(err);
      } else if (count) {
        return next();
      } else {
        res.redirect('/');
      }
  });
}

Upvotes: 1

Related Questions