Search code examples
node.jssequelize.jsmysql2

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


I'm trying to export data from a html form using sequelize and getting the following error: Cannot read property 'create' of undefined. I'm able to output the data in an object from the form just fine.

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
    //   } 
    }, 

Expect to create post to db named 'cupcakes', and table named 'orders'


Solution

  • Take a look at your orders.js file. It looks like you declared this variable

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

    And you are trying to access db.orders

    Looks like you should try accessing db.Orders instead.

    I have used sequelize a lot. Their models all start with a Capital letter. You may be able to configure it otherwise, but this is the default behavior.

    If you are still having issues, try doing a console.log on db and see what you get.

    console.log(db)