I have a loop where fields in a mongoDB document is updated using the req sent by the user.
I am using mongoose to manage the DB.
Here is the code
router.put("/edititem", async (req, res) => {
try {
const newMenuItem = await menuItems.findById(req.body._id);
for (key in req.body) {
if (key === "_id") continue;
console.log(newMenuItem.key);
req.body.key ? (newMenuItem.key = req.body.key) : null;
}
newMenuItem.save();
res.status(200).json(newMenuItem);
} catch (error) {
res.status(500).json(error);
}
});
What it should do:
- Change the specified keys in the specified document.
What it is doing:
- The value of keys are
undefined
inside the loop.