尝试使用 sequelize 存储用户时出现意外错误

Unexpected error while trying to store user with sequelize

我对 node.js 和 js 中的 sequelize 和 promises 比较陌生。但是我不明白为什么我的程序在成功创建用户后仍返回我的错误消息。

我的续集模型,阅读文档和这里的一些答案我添加了钩子来加密密码:

const Sequelize = require('sequelize');
const bcrypt = require('bcrypt');

const db = require('../util/config');

const User = db.define('user', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  userName: {
    type: Sequelize.STRING(250),
    allowNull: false
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  type: {
    type: Sequelize.INTEGER,
    allowNull: false
  }
},
  {
    hooks: {
      beforeCreate: async (user) => {
        const hashedPassword = await bcrypt.hash(user.password, 8);
        user.password = hashedPassword;
      }
    }
  }
);
module.exports = User;

这是我用来存储用户的中间件

const User = require('../models/user');
const Patient = require('../models/patient');
const bcrypt = require('bcrypt');

exports.newUser = (req, res, next) => {
  const errors = validationResult(req);
  console.log('REQUEST', req.body);
  if (errors.isEmpty()) {
    checkPerson(req.body).then((existPerson) => {
      if (existPerson) {
        checkUser(req.body).then((existUser) => {
          if (!existUser) {
            User.create(req.body)
              .then((res) => {
                res.status(201).json({ // 201 = OK, pero creado un recurso
                  message: 'Saved successfully',
                  data: {
                    generatedId: res.dataValues.id,
                    patientCreated: res.dataValues
                  }
                })
              })
              .catch((error) => {
                res.status(400).json({
                  message: 'Error while creating user',
                  DBError: error
                })
              });
          } else {
            res.status(200).json({
              message: 'The person already has an user, please login'
            })
          }
        })
      } else {
        res.status(200).json({
          message: 'No person found with that id',
        })
      }
    })
  } else {
    res.status(502).json({
      message: 'Data validation error',
      validationErrors: errors.array()
    })
  }
}

function checkPerson(payload) {
  // console.log('checkPerson payload', payload)
  const userType = +payload.type;
  switch (userType) {
    case 1: // PATIENT
      return new Promise(resolve => {
        resolve(
          Patient.findOne({
            where: {
              id: payload.patientId
            }
          }).then(user => { return user ? true : false })
        )
      })
  }
}

function checkUser(payload) {
  return new Promise(resolve => {
    resolve(
      User.findOne({
        where: {
          patientId: payload.patientId,
        }
      }).then((user) => {
        return user ? true : false;
      })
    )
  })

}

我的中间件检查患者(在本例中)是否存在,然后检查患者是否有用户,如果没有,则创建用户。但是我得到的响应是 'Error while creating user',但是如果我检查数据库,则用户已成功创建,但我不知道为什么,我们将不胜感激。提前致谢

看起来问题出在 then 子句中。不要对 User.create 响应和 HTTP 响应都使用 res,您应该将其更改为其他内容,例如:

.then((createResponse) => {
    res.status(201).json({ // 201 = OK, pero creado un recurso
        message: 'Saved successfully',
        data: {
            generatedId: createResponse.dataValues.id,
            patientCreated: createResponse.dataValues
        }
    })
})