I’m having difficulty replacing a field with mongoose/mongodb
I have some documents that look like this:
{account:1234, myArray:[a,b,c]}
const newArray = [d,e,f];
const result = await Model.updateMany({
account:1234,
}, {
$set:{
// 'testUpdating':4,
'myArray':newArray,
}
});
I get this back as a result:
{
"ok": 0,
"n": 0,
"nModified": 0
}
However if i uncomment the testUpdating:4
update, i get the expected result of having updated 18k documents, however only the ‘testUpdating’ field was modified.
I’m either doing something wrong, or it’s just refusing to update the array field with a new array.
2
Answers
Example with
update()
is working:upsert : true
means If record in not found then record will be created.upsert : false
means if record is not found then record will not be created.In basic terms it is
insert + update = upsert
multi:true
to update multiple documents whereasmulti:false
it will update single document.Data:
Update Aggregate:
Output:
Your
Model.updateMany()
looks fine and should update all matching documents with your desired result.This is probably a case of schema definition issues.
Make sure you define your
myArray
property with an array of types you actually want and you need to pass those data types to yourupdateMany
. For example, if yourmyArray
is an array of strings your schema will look similar to this:Then when you do your
updateMany
make sure you pass in an an array of strings like this:If you want to store an array of different types (not strings) then look at the docs for an example of options available.