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

NodeJS Sequelize - Fetch the ID from the row just created in MySQL?

目前,我的代码 return 是一条消息 'Registration successful'。我怎样才能 return 我刚刚在 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 函数实际上 return 什么也没有。您应该做的是更新该函数,使其 return 成为新创建的 ID,或已经存在的 ID(如果您需要)。

accountService.register(req.body, req.get('origin'))
    .then(() => res.json(account.id));

您已经测试过的这部分代码不起作用,因为 account.then 承诺解决方案中缺失。此外,由于您的方法没有 return 任何内容,因此您将无法访问 .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 存在,则您当前保存的是散列和明文的帐户密码,应避免这种情况