Reputation: 90
I'm trying to update the status of a product (Product table). Every product has a statusId, which is "1" or "2".
The default value for the statusId is "1" for every product and should change to "2" if the route is accessed once (and vice versa).
"statusId" and "status"{"id"} should always be the same.
When I access the route, the status is changed in the database and for "statusId", but the HTTP Response for "status" is different from the actual value in the database.
Example Response:
{
"id": 1,
"name": "Drone",
"barcode": "123456789",
"description": "A drone that can fly",
"image": "drone.jpg",
"createdAt": "2020-12-22T17:30:15.000Z",
"updatedAt": "2020-12-22T17:30:22.841Z",
"statusId": 2,
"status": {
"id": 1,
"name": "in",
"createdAt": "2020-12-22T17:30:15.000Z",
"updatedAt": "2020-12-22T17:30:15.000Z"
}
}
Association:
db.status.hasMany(db.product, {
foreignKey: {allowNull: false} ,
});
db.product.belongsTo(db.status, {
foreignKey: {allowNull: false}
});
Route:
app
.route('/api/product/status/:id')
.put([authJwt.verifyToken], controller.updateProductStatus);
Controller:
exports.updateProductStatus = (req, res) => {
// Get product with id and update status only
Product.findOne({
where: {
id: req.params.id
},
include: [
Status
]
})
.then(product => {
let newStatus = product.statusId === 1 ? 2 : 1;
product.update({
statusId: newStatus
})
.then(
res.status(200).send(product)
)
.catch(err => {
console.log("Error (Update product): " + err);
res.status(404).send(err);
})
})
.catch(err => {
console.log("Error (find old product): " + err);
res.status(404).send(err);
});
};
How can I change my code to return the correct value for the "id" of "status"?
Thank you in advance!
Upvotes: 2
Views: 898
Reputation: 22813
You should reload a model instance like this:
.then(
product.reload({ include: [Status]})
.then(res.status(200).send(product))
)
Upvotes: 2