I'm learning "Sequelize". I went through documentation and got this code somewhere else.
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body).then(
result => {
res.status.json({data: result})
}).catch(err => console.log(err))
}
but I want this in the below structure,
Model = require('../models/Salesman')
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body, function (result, err) {
if (err) {
console.log(err)
}
else {
res.status.json({data: result})
}
});
}
I tried this,.it didn't send the response. But inserted the data correctly to db. How to get the response in this case.?
CodePudding user response:
The Model.create
method returns a Promise
, and does not have a callback parameter.
So you either handle the Promise
with then:
module.exports.creareSalesman = (req, res, next) => {
Model.create(req.body)
.then((result) => {
res.status.json({ data: result });
})
.catch((err) => console.log(err));
};
Or use async await
:
module.exports.creareSalesman = async (req, res, next) => {
try {
const result = await Model.create(req.body);
res.status.json({ data: result });
} catch (err) {
console.log(err);
}
};