mysql - NodeJS Sequelize - 从刚刚在 MySQL 中创建的行中获取 ID?

标签 mysql node.js sequelize.js

目前,我的代码返回一条消息,显示“注册成功”。如何返回我刚刚在 MySQL 中创建的行的 id?

function register(req, res, next) { 
    accountService.register(req.body, req.get('origin'))
        .then(() => res.json({ message: 'Registration successful' }))
        .catch(next);
}
这是模型;
const { DataTypes } = require('sequelize');

module.exports = model;

function model(sequelize) {
    const attributes = {
        id: {type: Sequelize.INTEGER,primaryKey:true,autoIncrement: true,allowNull: false},
        email: { type: DataTypes.STRING, allowNull: false },
        passwordHash: { type: DataTypes.STRING, allowNull: false },
        name: { type: DataTypes.STRING, allowNull: false },
        gavatar: { type: DataTypes.STRING, allowNull: false },               
        role: { type: DataTypes.STRING, allowNull: false },
        verificationToken: { type: DataTypes.STRING },
        verified: { type: DataTypes.DATE },
        resetToken: { type: DataTypes.STRING },
        resetTokenExpires: { type: DataTypes.DATE },
        passwordReset: { type: DataTypes.DATE },
        created: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
        updated: { type: DataTypes.DATE },      
        isVerified: {
            type: DataTypes.VIRTUAL,
            get() { return !!(this.verified || this.passwordReset); }
        }
    };

    const options = {
        timestamps: false, 
        defaultScope: {
             attributes: { exclude: ['passwordHash'] }
        },
        scopes: {
            withHash: { attributes: {}, }
        }        
    };

    return sequelize.define('account', attributes, options);
}
我试过这个;accountService.register(req.body,req.get('origin')).then(()=>res.json(account.id))但是我收到了一个错误提示;
"message":"Cannot read property 'findOne' of undefined"
这是 account.service.js 中的注册函数;
async function register(params, origin) {
  
    if (await db.Account.findOne({ where: { email: params.email } })) {
        return await sendAlreadyRegisteredEmail(params.email, origin);
    }

    const account = new db.Account(params);

    const isFirstAccount = (await db.Account.count()) === 0;
    account.role = isFirstAccount ? Role.Admin : Role.User;
    account.verificationToken = randomTokenString();

    account.passwordHash = await hash(params.password);

    await account.save();
    
    await sendVerificationEmail(account, origin);
  }
我不确定在哪里可以找到 ID。

最佳答案

根据您更新的代码,您的 .register 函数实际上没有返回任何内容。您应该做的是更新该函数,使其返回新创建的 ID 或已经存在的 ID(如果需要)。

accountService.register(req.body, req.get('origin'))
    .then(() => res.json(account.id));
您已经测试过的这部分代码不起作用,因为 account promise 解析中缺少 .then。此外,由于您的方法不返回任何内容,您将无法访问 .then(() => {}) 回调中的任何内容。
您可以尝试更新 register 函数如下
async function register(params, origin) {
  const existingAccount = await db.Account.findOne({
      where: { email: params.email }
  });
  if (existingAccount) {
    await sendAlreadyRegisteredEmail(params.email, origin);
    return existingAccount.id;
  }

  const isFirstAccount = (await db.Account.count()) === 0;

  const accountParams = {
    ...params,
    role: isFirstAccount ? Role.Admin : Role.User,
    verificationToken: randomTokenString(),
    passwordHash: await hash(params.password)
  }
  
  const account = await db.Account.create(
    accountParams, { isNewRecord: true }
  );

  await sendVerificationEmail(account, origin);
  
  return account.id;
}
并更新您的 API 处理程序如下
accountService.register(req.body, req.get('origin'))
    .then((id) => res.json({id}))
请注意,如果 params.password 存在,您当前正在保存帐户密码散列和明文,应避免

关于mysql - NodeJS Sequelize - 从刚刚在 MySQL 中创建的行中获取 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67300052/

相关文章:

database - node.js sequelize 在迁移时没有主键

mysql - 用于根据多行查找匹配结果的 SQL 查询

MySQL:Grant Privileges followed by Flush Privileges 没有效果,没有错误(以 root 身份登录)

mysql - 处理进度条上显示的 MySQL 查询

node.js - 在 Node.js 中的 for 循环中进行异步操作,而不使用异步库帮助程序类

javascript - Node.js 中的 sqlite3 不从 INSERT 回调返回 lastID

mysql - NodeJS 和 MySQL : Importing CSV data with associations

mysql - 如何按 MAX(日期)选择?

php - 变量在函数内未定义,无法在函数内到达 MySQL $connection

javascript - Node.js/JavaScript - Java 的 Jackson 等价物