i would like to update and element in array of objects if it is already in the array.
For now what i'm doing is this :
exports.pushDocumentsList = (req, res) => {
const documents = [];
documents.push({
_id: req.body.document._id,
fileid: req.body.document.fileid,
filename: req.body.document.filename,
url: req.body.document.url ? req.body.document.url : '',
status: req.body.document.status ? req.body.document.status : '',
expiredate: req.body.document.expiredate
? req.body.document.expiredate
: '',
});
User.findOneAndUpdate(
{
_id: req.profile._id,
},
{ $push: { documents } },
{ new: true, useFindAndModify: false },
(err, docu) => {
console.log(docu);
if (err) {
return res.status(400).json({
error: "Non è stato possibile aggiornare i documenti dell'utente",
});
}
return res.status(200).json({
status: 'success',
message: 'Documento caricato con successo',
doc: req.body.document,
});
}
);
};
So this only appends the element to the array , i would like to know how can i update the element if it's already in the array.
you can do it with. notation and $eleMatch
example with dot:
const user = await User.findOneAndUpdate(
{ _id: req.profile._id, "documents._id": "someId" },
{
$set: {
"documents.$.filename": "file changed"
"documents.$.status": "status will change",
},
}, //update
{ new: true } //options
);