I have this code that loop through all users in DB then look for specific events based on the id value and if there is a match it should update the field caption with a new given data,
for the code :
1- search all potential user = OK
2 - search and find events based on id = OK
3- update the field caption = NOK
this is my code hope I mentioned everything
router.post('/delete/:id',async (req, res) => {
const eventId = req.params.id // this is the ID of the event
User.find({}).lean(true).exec((err, users) => {
let getTEvent = [];
for (let i = 0; i < users.length; i++) {
if (users[i].events && users[i].events.length) {
for (let j = 0; j < users[i].events.length; j++) {
if (users[i].events[j]._id === eventId) {
console.log('you event is :'+ eventId) // this statement to verify if really got the correct ID or not
users[i].events[j].caption ="deleted" // from here the problem
users[i].save(err => {
if (err) throw err;
console.log("status changed saved");
// Redirect back after the job is done.
});
}
}
}
}
});
})
the error that I get is that users[i].save is not a function I don't know with what should I replace it,
As per comments @whoami
router.post('/delete/:id', (req, res) =>
User.findOneAndUpdate({
"events._id": req.params.id
},
{ $set: { "events.caption": "yesssss" }
}, {upsert: true}, (err, user) => {
if (err) {
res.send('error updating ');
} else {
console.log(user);
console.log(req.params.id)
}
}));
Below the mongoDb and event datastructure
Hope I clarified everything ,
Best Regards,


.save()works on mongoose document but not on javaScript object, In your code you've already converted mongoose documents returned from find call to .Js objects using :.lean(true)!! You can use.findOneAndUpdate()with a unique filter to find particular user document & update entireeventsarray. Or more simple instead of reading all docs & iterating in code (Which is not preferred at all) you can take advantage of same.findOneAndUpate()to update docs in just one DB call..