I use the following function in an API I am building
const editUserInfo = catchAsync(async(req, res, next) => {
const userId = req.user.id;
const body = req.body;
const result = await user.findByPk(userId);
result.userName = body.userName;
result.email = body.email;
const updatedResult = await result.save();
console.log(updatedResult.toJSON())
...
The username and email fields of my model are identified as unique in both the model definitions and the migrations file, and I have verified that the Database is constraining them as unique. The catchAsync
wrapper function should be catching the validation error, and does so when I attempt to create()
new instances that violate the constraints.
However, in this function, despite result.save()
never sending an UPDATE query to my DB, updatedResult is set to the original model, and no error is reported.
For example, when
{
username: 'JWick',
email: '[email protected]',
}
is sent, despite JWick already existing in the database, the function reports a success code while not actually sending the update to the DB
I would hope that it would report an error so that the API can tell the front-end that the operation failed, but I'm not sure how to go about that
I use the following function in an API I am building
const editUserInfo = catchAsync(async(req, res, next) => {
const userId = req.user.id;
const body = req.body;
const result = await user.findByPk(userId);
result.userName = body.userName;
result.email = body.email;
const updatedResult = await result.save();
console.log(updatedResult.toJSON())
...
The username and email fields of my model are identified as unique in both the model definitions and the migrations file, and I have verified that the Database is constraining them as unique. The catchAsync
wrapper function should be catching the validation error, and does so when I attempt to create()
new instances that violate the constraints.
However, in this function, despite result.save()
never sending an UPDATE query to my DB, updatedResult is set to the original model, and no error is reported.
For example, when
{
username: 'JWick',
email: '[email protected]',
}
is sent, despite JWick already existing in the database, the function reports a success code while not actually sending the update to the DB
I would hope that it would report an error so that the API can tell the front-end that the operation failed, but I'm not sure how to go about that
Catch SequelizeUniqueConstraintError
explicitly to handle constraint violations