You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Sequelize+MySQL+Node调用findOne时出现undefined错误求助

嘿,我看到你的问题了——用户明明创建成功,但findOne返回undefined,导致拿不到id报错。咱们一步步揪出问题根源,再给出修复方案:

核心问题:Promise链式调用逻辑错误

你在db.user.create()的.then()里直接嵌套了db.user.findOne()的Promise,这相当于让findOne在create还没完成时就执行了!这时候数据库里还没新增用户,自然查不到结果。

而且更高效的是:create方法本身会返回刚创建的用户实例,完全没必要再额外调用findOne去查一次数据库!直接用create返回的对象就能拿到id。

其他潜在问题

  1. 异步错误无法被捕获
    你用了bcrypt.hash的回调函数,外面的try/catch根本抓不到回调内部的异步错误。建议改用bcrypt的Promise版本,配合async/await让代码更简洁易维护。

  2. express-validator用法过时
    你用的req.check()和req.validationErrors()是旧版本写法,新版本推荐把验证规则作为中间件使用,代码结构更清晰。

  3. req.body定义位置错误
    你把var input = req.body;放在了路由函数外面,这时候req还未被定义,会直接报错,应该放到路由处理函数内部直接使用req.body。

修复后的完整代码

const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const session = require('express-session');
const { check, validationResult } = require('express-validator');
const db = require("../models/index");

// 注册路由
router.post('/register',
  // 验证规则(带友好错误提示)
  check('firstName').isLength({ min: 1, max: 100 }).withMessage('名字长度需在1-100字符之间'),
  check('lastName').isLength({ min: 1, max: 100 }).withMessage('姓氏长度需在1-100字符之间'),
  check('email').isEmail().withMessage('请输入有效的邮箱地址'),
  check('username').isLength({ min: 1, max: 15 }).isAlphanumeric().withMessage('用户名需为字母数字组合,长度1-15字符'),
  check('password').isLength({ min: 8, max: 100 }).withMessage('密码长度至少8位'),
  
  async (req, res) => {
    try {
      // 检查验证结果
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }

      // 哈希密码(async/await版)
      const saltRounds = 10;
      const hashedPassword = await bcrypt.hash(req.body.password, saltRounds);

      // 创建用户,直接拿到新用户实例
      const newUser = await db.user.create({
        first_name: req.body.firstName,
        last_name: req.body.lastName,
        email: req.body.email,
        username: req.body.username,
        hashed_password: hashedPassword
      });

      // 为新用户创建会话(根据你的session配置调整)
      req.session.userId = newUser.id;
      res.status(201).json({ 'created user': newUser.id });

    } catch (error) {
      console.error('服务器错误:', error);
      res.status(500).json({ message: '服务器发生错误' });
    }
  }
);

module.exports = router;

内容的提问来源于stack exchange,提问作者user4747724

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:27:34