猫鼬保存不起作用

时间:2015-08-23 08:46:18

标签: node.js express mongoose

刚开始使用Node,Express和Mongoose。

Mongoose版本:4.1.3

这是我的模特

  var mongoose = require('mongoose'),
    bcrypt = require('bcrypt'),
    ObjectId = mongoose.Schema.Types.ObjectId,
    Timestamp = global.requireLib('timestamp');


var UserSchema = mongoose.Schema({
  email: {type: String, required: true, unique: true},
  password: {type: String, required: true},
  first_name: {type: String},
  last_name: {type: String},
  username: {type: String, unique: true},
  role: {type: String, required: true, default: 'user'},
  created_at: {type: Number, required: true, default: Timestamp.now()},
  updated_at: {type: Number, required: true, default: Timestamp.now()}
});


UserSchema.methods.hashPassword = function () {
  salt = bcrypt.genSaltSync(13);
  this.password = bcrypt.hashSync(this.password, salt);
}


UserSchema.methods.validate = function (password) {
  return bcrypt.compareSync(password, this.password);
}


var User = mongoose.model('User', UserSchema, 'users');


module.exports = User;

这是'控制器'方法:

   create: function (req, res) { 
      User.findOne({email: req.body.email}, function (err, user) {
        if (err) {
          res.error('UnknownError');
        } else if (!user) {
          user = new User(req.body);
          user.hashPassword();
          user.save(function (err) {
            if (err) {
              res.error('UnknownError');
            } else {
              res.success({id: user.id});
            }
          });
        } else {
          res.error('EmailExists');
        }
      });
    },

请求:

curl -X POST -H 'Content-type: application/json' -d '{"email": "user@example.com", "password": "123"}' http://localhost:3000/users

路由工作正常,如果我在create function的开头添加console.log(),我将在控制台中看到它。如果我做console.log(user.save) - 我会说,它是一个函数。但没有任何记录MongoDB。更新工作正常,如果我用upsert更新 - 没关系。

还剩6个小时,仍然无法找到错误。

2 个答案:

答案 0 :(得分:0)

user.save(function (err) {
    if (err) {
        console.log(err);
        res.send(err);
    }
    else {
        console.log(user.id);
        res.success({id: user.id});
    }
});

更新代码并检查您在控制台中获得的错误

答案 1 :(得分:0)

您是否可以尝试将 next()添加到hashPassword这样的功能中?

UserSchema.methods.hashPassword = function () {
    salt = bcrypt.genSaltSync(13);
    this.password = bcrypt.hashSync(this.password, salt);
    next();
}
相关问题