KitKit
KitKit

Reputation: 9563

SequelizeJS: How to know success or failure when executing an INSERT raw query?

I use PosgreSQL. Now I have an INSERT raw query. I want to know ask 2 questions:

  1. I want to know if it is success or failure when executing it
  2. If success, I want to get the new data I inserted

    var querydb = INSERT INTO chat_message VALUES (DEFAULT, '${text}', '${created_at}', '${room_id}', '${user_id}');

    sequelize.query(querydb, { type: sequelize.QueryTypes.INSERT}) .then(insertID => { resolve(insertID) }) .catch(err => { reject(err) })

Upvotes: 0

Views: 1576

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

First of all you shouldn't be using raw queries until unless you are not able to do anything with sequelize.js , or else there is no use of using this library.

Use sequelize.js as much as possible , so that you can use default functionality very easily.

So this is how you can do the same thing in sequelize.js way :

ChatMessage.create({
    text: text,
    room_id: room_id,
    user_id: user_id
    created_at: new Date() // Not required , it will be auto managed by sequlize
}).then(message => {
    console.log(message);
    // you can now access the newly ChatMessage task via the variable message
}).catch(err => {
    // catch error if anything goes wrong
})

Upvotes: 1

Related Questions