I am attempting to add a new field into every object within an array only when that field does not already exist. I am trying to use updateMany
but the below script does not seem to work…
The logic should be, for every object in the array ss_characteristics
, if the field new_field
is not present, add it with an empty string value.
Please help!
const updateResult = await Form.updateMany(
{},
{ $set: { "ss_characteristics.$[elem].new_field": '' } },
{ arrayFilters: [{ "elem.new_field": { $exists: false } }] }
);
console.log('updateResult: ', util.inspect(updateResult, false, null));
// that logs the below:
// updateResult: { acknowledged: false }
const all_forms = await Form.find({})
// logging all_forms will give me something similar to below:
[
{
ss_characteristics: [
{ name: 'test 1' },
{ name: 'test 2', new_field: 'No'}
]
},
{
ss_characteristics: [
{ name: 'test 3' , test_field: ''},
{ name: 'test 4' },
]
},
{
ss_characteristics: []
}
]