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.
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 your updateMany
. For example, if your myArray
is an array of strings your schema will look similar to this:
const schema = new mongoose.Schema({
account: {
type: Number
},
testUpdating: {
type: Number
},
myArray: [String] //< An array of strings i.e. ['a', 'b', 'c']
});
Then when you do your updateMany
make sure you pass in an an array of strings like this:
const newArray = ['d', 'e', 'f']; //< An array of strings
const result = await Model.updateMany({
account:1234,
}, {
$set:{
'testUpdating':4,
'myArray':newArray,
}
});
If you want to store an array of different types (not strings) then look at the docs for an example of options available.