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

ExpressJS/Sequelize模型导入失败:调用create方法报错

Sequelize模型调用报错:Cannot read properties of undefined (reading 'create')

问题场景

使用Express+Sequelize+REST API搭建全栈项目时,编写了PaymentMethods模型用于处理POST请求,调用db.PaymentMethods.create()时触发错误"Cannot read properties of undefined (reading 'create')",改用update方法仍报错,其他同结构模型可正常使用,需实现向payment_methods表插入数据。

模型代码

module.exports = (sequelize, DataTypes) => {
  const PaymentMethods = sequelize.define("payment_methods", {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    cardnumber: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    expirydate: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    CVC: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  }, {
    timestamps: false
  });

  return PaymentMethods;
};

路由代码

const express = require('express');
const router = express.Router();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const db = require('../models');

router.post('/payment/updatepaymentmethod', async (req, res) => {
  try {
    const { email, cardNumber, expDate, cvc } = req.body;

    // Create a new payment method record in the database
    const newPaymentMethod = await db.PaymentMethods.create({
      email: email,
      cardnumber: cardNumber,
      expirydate: expDate,
      CVC: cvc
    });

    // Return success response
    res.status(200).json({
      success: true,
      message: 'Payment method updated successfully',
      paymentMethod: newPaymentMethod
    });
  } catch (error) {
    console.error('Error during payment method update:', error);

    // Log the error object for debugging
    console.log(error);

    res.status(500).json({
      success: false,
      message: 'Payment method update failed',
      error: error.message
    });
  }
});

module.exports = router;

模型索引文件代码

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const process = require('process');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      file.slice(-3) === '.js' &&
      file.indexOf('.test.js') === -1
    );
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

解决方案

错误根源是模型在db对象中的引用名称不匹配:

方案1:修正路由中的模型引用

Sequelize默认会将sequelize.define()的第一个参数(表名)作为模型的name属性,所以当前db对象中模型的键是payment_methods,而非PaymentMethods。修改路由中的调用代码:

// 原代码
const newPaymentMethod = await db.PaymentMethods.create({...});

// 修改后
const newPaymentMethod = await db.payment_methods.create({
  email: email,
  cardnumber: cardNumber,
  expirydate: expDate,
  CVC: cvc
});

方案2:手动指定模型名称(保持驼峰命名)

如果希望继续使用db.PaymentMethods的调用方式,可在模型定义的options中添加modelName字段,显式指定模型名称:

module.exports = (sequelize, DataTypes) => {
  const PaymentMethods = sequelize.define("payment_methods", {
    email: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    cardnumber: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    expirydate: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    CVC: {
      type: DataTypes.STRING,
      allowNull: false,
    },
  }, {
    timestamps: false,
    // 添加这一行,指定模型名称
    modelName: 'PaymentMethods'
  });

  return PaymentMethods;
};

修改后,路由中的db.PaymentMethods.create()即可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:10:53