尝试 post 到 mysql db 时出错:"Cannot read property 'create' of undefined"

Getting error when trying to post to mysql db: "Cannot read property 'create' of undefined"

我正在尝试使用 sequelize 从 html 表单导出数据并收到以下错误:无法读取未定义的 属性 'create'。我能够很好地从表单输出对象中的数据。

routes.js


var db = require("../models");

module.exports = function(app) {
app.post("/api/orders", function(req,res) {
console.log(req.body);

db.orders.create({
  date: req.body.date,
  billingAddress: req.body.billingAddress,
  city: req.body.city,
  state: req.body.state,
  email: req.body.email,
  cupcakeType: req.body.cupcakeType,
  quantity: req.body.quantity,
  specialInstructions: req.body.specialInstructions,
  totalPrice: req.body.totalPrice,
  card: req.body.card,
  cardNumber: req.body.cardNumber,
  cvc: req.body.cvc,
  CustomerID: req.body.CustomerID
})
  .then(function(dbOrders){
  console.log(dbOrders);
  res.json(dbOrders);
});
});

orders.js


module.exports = function(sequelize, DataTypes) {

var Orders = sequelize.define("Orders", {

date: {
  type: DataTypes.DATEONLY,
  allowNull: false
},
billingAddress: {
  type: DataTypes.STRING,
  allowNull: false,      
},
city: {
type: DataTypes.STRING,
allowNull: false, 
},
state: {
  type: DataTypes.STRING,
  allowNull: false, 
  }, 
email: {
    type: DataTypes.STRING,
    allowNull: false,
    // validate: {
    //   isEmail: true
    //   } 
    }, 

期望创建 post 到名为 'cupcakes' 的数据库,table 名为 'orders'

查看您的 orders.js 文件。看起来你声明了这个变量

var Orders = sequelize.define("Orders", {...

您正在尝试访问 db.orders

看来您应该尝试访问 db.Orders

我经常使用sequelize。他们的模型都以大写字母开头。您也许可以配置它,但这是默认行为。

如果您仍然遇到问题,请尝试在 db 上执行 console.log 并查看结果。

console.log(db)

试试这个

var db = require("../models");

module.exports = function(app) {
app.post("/api/orders", function(req,res) {
console.log(req.body);

db.Orders.create({
  date: req.body.date,
  billingAddress: req.body.billingAddress,
  city: req.body.city,
  state: req.body.state,
  email: req.body.email,
  cupcakeType: req.body.cupcakeType,
  quantity: req.body.quantity,
  specialInstructions: req.body.specialInstructions,
  totalPrice: req.body.totalPrice,
  card: req.body.card,
  cardNumber: req.body.cardNumber,
  cvc: req.body.cvc,
  CustomerID: req.body.CustomerID
})
  .then(function(dbOrders){
  console.log(dbOrders);
  res.json(dbOrders);
});
});