I’m trying to update an object within an array in a MongoDB database. I don’t seem to be getting very far with Googling the problem, and Mongo doesn’t seem to be coming back with any errors so I’m a bit stuck.
Here’s my code:
const { SnagList } = require("../models/schemaModel.js");
//get the details of the snag update from the request object, get the relevant customer from the database, loop through the snags array and update with the new info we just received in the request
const snagUpdate = async (req, res) => {
const snagId = req.body.update.id;
const snagLocation = req.body.update.location;
const snagDescription = req.body.update.snagDetails;
try {
const list = await SnagList.findById(req.body.customerId);
list.snags.forEach((snag) => {
if (snag.id === snagId) {
snag.location = snagLocation;
snag.snagDetails = snagDescription;
}
});
await list.save();
res.send("Snag update processed");
} catch (err) {
console.error(err);
res.send("Error during update process");
}
};
module.exports = snagUpdate;
so what I’m trying to do is retrieve a ‘snaglist’ by ID, then loop through the list and make the modifications, then save it. When I save using save(), it seems to perform the operation because it doesn’t return any errors. The problem is that when I check the DB for the update, it hasn’t actually done anything.
If it helps solve anything, I tried to .push a new object to the list array and it seems to work fine. The mongoose docs don’t seem to mention anything about issues like this as far as I’m aware.
PIE is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.