Trying to make a simple patch request against a single document, and the request returns
{
"acknowledged": true,
"modifiedCount": 1,
"upsertedId": null,
"upsertedCount": 0,
"matchedCount": 1
}
This is the document I am trying to update
{
"_id": "63843e60079d9cdf9c26505a",
"name": "AKG_HSD271",
"image": "images/Products/AKG_hsd271.png",
"colour": "Black",
"description": "AKG HSD271 over-ear headset",
"price": "165.99",
"startingDateAvailable": "2022-05-10T15:23:28.000Z",
"type": "Over-Ear",
"isOnSale": false,
"stock": 46,
"EndingDateAvailable": "N/A",
"manufacturer": "AKG",
"updatedAt": "2022-12-03T08:48:35.302Z"
}
This is the request body I am sending (via Postman)
{
"price": "100.99"
}
And here is the code for my route handler
router.patch('/Products/:id', (req, res) => {
console.log('/Products/' req.params.id);
const updates = req.body;
Product.updateOne({_id: ObjectId(req.params.id)}, {$set: updates})
.then(result => {
console.log(result);
res.json(result);
})
.catch(err => {
res.status(500).send(err.message);
});
});
Can't for the love of me figure out what is going wrong and why the price field won't change, and can't find any threads that have a suggestion I haven't tried. Any ideas?
CodePudding user response:
Try with:
router.patch('/Products/:id', (req, res) => {
console.log('/Products/' req.params.id);
const { price } = req.body;
Product.updateOne({ _id: ObjectId(req.params.id) }, { price }, { new: true })
.then((result) => {
console.log(result);
res.json(result);
})
.catch((err) => {
res.status(500).send(err.message);
});
});
CodePudding user response:
Found the problem. Including the built in json() function in express before my route handlers seemed to do the trick:
router.use(express.json())
Apparently in express, the body property does not exist on the req object unless you include the json middleware. Hope this helps others.