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?
CodePudding user response:
This should help you:
Events.create(new_event)
.then((event) => {
response.id=event.id
response.msg = 'Adaugat cu succes!';
response.added = 1;
res.send(response);
})
.catch((err) => {
response.msg = err;
response.added = 0;
res.send(response);
});
you will get the created object as a parameter
CodePudding user response:
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?
CodePudding user response:
You will get easily user inserted data using below code
const result = await Events.create(new_event);
console.log(result.id);