NodeJS,Mongoose,Express:如果用户是新的,请检查数据库

时间:2016-12-21 22:56:13

标签: node.js express mongoose

我正在使用Mongoose和Express。

我想检查一下是否已经使用了用户名。

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

我的架构:

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 ]
});

1 个答案:

答案 0 :(得分:1)

假设您在请求正文中使用name属性传入json,以下代码将起作用。

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('/');
      }
  });
}