Open abdullahIsa opened 2 years ago
This is assuming that you mean to update a specific array field's array item of an object belonging to your your datastore. It's not pretty nor the most efficient but maybe something like (getting the pre-existing item might be the easiest way):
db.findOne(
{_id: idOfObjectToUpdate},
function (err, doc) {
if (!err) {
const originalEntryOfArray = doc[arrayFieldToUpdate].filter(item => item._id === replacementArrayItem._id)[0]
db.update(
{_id: idToUpdate},
{[arrayFieldToUpdate]: doc[arrayFieldToUpdate]
.filter(item => item._id !== replacementArrayItem._id) // id of array item you want to replace
.concat([{...originalEntryOfArray, ...replacementArrayItem }]) // the replacement goes here so the fields that need to be updated overwrite those of 'originalEntryOfArray'
}},
{upsert: upsert},
function (err, numAffected) {
resolve(!err);
},
);
}
},
);
Hello, thanks very much for this but I am looking for how to update an existing object in an array based on a value or query check, how can I get this done as
$addToSet
withdb.update()
is pushing a new one because the_id
are different and if I am correct as stated in the documentation it should replace the old object, so may I know what I am doing wrong or how may I add an additional query to update this, thanks very much.Example:
Old object in the array
New object coming from the server containing additional information that should replace or update the old one