'How to get back the object id after POST method using Sequelize and send it to frontend?

I try to post a new object in my MySQL database in React using Sequelize and I have this route:

app.post("/event", checkAuthorization, async (req, res) => {

    let new_event = {
        title: req.body.title,
        description: req.body.description,
        label: req.body.label,
        day: req.body.day,
        user_id: req.body.user_id,
    };

    let response = {};

    Events.create(new_event)
        .then(() => {
            response.msg = 'Adaugat cu succes!';
            response.added = 1;
            res.send(response);
        })
        .catch((err) => {
            response.msg = err;
            response.added = 0;
            res.send(response);
        });

});
  • checkAuthorization is to check if user is logged id

My problem is: I send an object without an id because is auto-increment in my database and all I want is after I post this object in database, to return to frontend the object id created by database and I don't know how to write that.

Can somebody help me, please?



Solution 1:[1]

I tried to used:

Events.create(new_event)
        .then((event) => {
            console.log(event);
            response.msg = 'Adaugat cu succes!';
            response.added = 1;
            res.send(response);
        })
        .catch((err) => {
            response.msg = err;
            response.added = 0;
            res.send(response);
        });

And this is the output:

event {
  dataValues: {
    id: null,
    title: 't',
    description: 'dsada',
    label: 'green',
    day: 1645653600000,
    user_id: 2
  },
  _previousDataValues: {
    title: 't',
    description: 'dsada',
    label: 'green',
    day: 1645653600000,
    user_id: 2,
    id: null
  },
  uniqno: 1,
  _changed: Set(0) {},
  _options: {
    isNewRecord: true,
    _schema: null,
    _schemaDelimiter: '',
    attributes: undefined,
    include: undefined,
    raw: undefined,
    silent: undefined
  },
  isNewRecord: false,
  null: 23
}

That 'null: 23' is my id and I don't know why database returns me the id like that... Can someone explain me?

Solution 2:[2]

You will get easily user inserted data using below code

const result = await Events.create(new_event);
console.log(result.id);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lungu Mihai Adrian
Solution 2 Mr.Developer