Search code examples
mysqlnode.jsexpresssequelize.js

Sequelize create() not working for inserting an order, but manual SQL query works


I am trying to create an order using Sequelize in my Node.js app, but I'm encountering issues with both the Order.create() method and a manual INSERT INTO query.

Here is the code I'm using to create an order:

let userId = 71;
let restaurantId = 43;
let status = 'submitted';
let items = '[{"itemName":"meal 1","itemDescription":"meal 1","itemPrice":2}, 
{"itemName":"drink 1","itemDescription":"drink 1","itemPrice":4},{"itemName":"drink 
1","itemDescription":"drink 1","itemPrice":4}]'

let order = await Order.create({
customerId: userId,
restaurantId: restaurantId,
status: status,
items: items,
});

However, this approach doesn’t work, and I am getting no clear error message. I thought a manual SQL query might work, so I tried the following:

const query = `
INSERT INTO orders (customerId, restaurantId, status, items)
VALUES (:customerId, :restaurantId, :status, :items);
`;

await sequelize.query(query, {
replacements: {
customerId: userId,
restaurantId: restaurantId,
status: status,
items: items,
},
type: QueryTypes.INSERT
});

This also doesn't work, and I don't see any results.

Interestingly, when I run the following manual query directly in MySQL Workbench, it works perfectly fine:

INSERT INTO Orders (customerId, restaurantId, status, items)
VALUES (71, 43, 'submitted', '[{"itemName":"meal 1","itemDescription":"meal 
1","itemPrice":2},{"itemName":"drink 1","itemDescription":"drink 1","itemPrice":4}, 
{"itemName":"drink 1","itemDescription":"drink 1","itemPrice":4}]');

here is my Order model in case there is something I am missing:

const Order = sequelize.define('Order', {

customerId:{
    type: DataTypes.INTEGER,
    allowNull: false,
    references:{
        model: 'Users',
        key: 'id'
    },
    onDelete:'CASCADE',
    onUpdate: 'CASCADE'
},
restaurantId:{
    type: DataTypes.INTEGER,
    allowNull: false,
    references:{
        model: 'Restaurants',
        key: 'id'
    },
    onDelete:'CASCADE',
    onUpdate: 'CASCADE'
},
status:{
    type: DataTypes.STRING,
    allowNull: false,
    defaultValue: "pending"

},
items:{
    type: DataTypes.JSON,
    allowNull: false
},

}, { timestamps: true,

});

Any help or insights would be greatly appreciated. Thanks in advance!


Solution

  • The solution was to drop Orders table and recreate it using the update Order model definition, I have made sure to make and run migration files to prevent this from happening, but it seems I missed a step somewhere, or the migration files simply glitched. the Orders table simply needed to be recreated!