簡體   English   中英

使用mongooseSchema.pre('save')方法時,node.js中未處理的承諾拒絕

[英]Unhandled promise rejection in node.js while using mongooseSchema.pre('save') method

//This is the user model
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const userSchema = mongoose.Schema({
  email: {
    type: String,
    index: {
      unique: true
    }
  },
  password: {
    type: String
  }
});

userSchema.pre("save", function(next) {
  var user = this;
  if (!user.isModified("password")) {
    return next();
  }

  bcrypt.genSalt(saltRounds, function(err, salt) {
    if (err) {
      return next(err);
    }
    bcrypt.hash(user.password, salt, salt, function(err, hashedPassword) {
      if (err) {
        return next(err)
      }
      user.password = hashedPassword;
      next();
    });
  });
});

userSchema.methods.checkPassword = function(guess, cb) {
  bcrypt.compare(guess, this.password, function(err, isMatch) {
    cb(err, isMatch);
  });
};
const User = mongoose.model('User', userSchema);
module.exports = User;


//The code below  is the /signup route
router.post('/signup', (req, res) => {
  User.findOne({
    email: req.body.email
  }, (err, user) => {
    if (err) {
      throw err;
    }

    if (user) {
      // handle case for user already exists!!
      res.json({
        success: false,
        message: 'An account with this email already exists'
      });
    } else {
      var newUser = new User({
        email: req.body.email,
        password: req.body.password
      });

      newUser.save((err) => {
        if (err) {
          return res.send(err);
        }
        let jwtData = {
          email: req.body.email
        };

        let token = jwt.sign(jwtData, jwtSecret);

        res.json({
          success: true,
          token: token
        });
      });
    }
  });
});

當我向/ signup路由發出發布請求時,在nodejs版本8.1.2中出現此錯誤:

(節點:8317)UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:1):錯誤:cb必須為函數或為null才能返回Promise

如果我刪除貓鼬的前置方法,則該路線會正常運行。 但是我想對密碼進行哈希處理。在這個問題上請幫幫我。謝謝

您的預保存回調函數使用一個名為“ done”的函數,但是您正在調用“ next”。

它應該是:

userSchema.pre("save", function(next) {
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM