Home > Net >  Mongo error :Modifiers operate on fields but we found type array instead
Mongo error :Modifiers operate on fields but we found type array instead

Time:11-04

I'm working with node and mongo 5.0 . I have a preexisting record that I want to add 2 fields to. I am trying to insert 2 numbers (due, assessed) into the fields Owed and Yearly. These 2 fields do not currently exist within each record. I tried multiple variations including:

        await collection.updateOne({ _id: record._id }, { $set: [{ "Owed": due}, {"Yearly": assessed }]});

which gives:

'MongoServerError: Modifiers operate on fields but we found type array instead. For example: {$mod: {<field>: ...}} not {$set: [ { Owed: 0 }, { Yearly: 466.64 } ]}\n    

How to I add multiple fields to a record here?

Edit:

I changed my code to yours. Now I am seeing:

MongoServerError: Modifiers operate on fields but we found type array instead. For example: {$mod: {<field>: ...}} not {$set: [ { Owed: 0 }, { Yearly: 466.64 } ]}

Any thoughts?

CodePudding user response:

I guess you should pass 3rd paramater upsert to create field if it doesn't exists.

await collection.updateOne({ _id: record._id }, { $set: [{ "Owed": due}, {"Yearly": assessed }]}, {upsert: true});

CodePudding user response:

Based on https://www.mongodb.com/docs/manual/reference/operator/update/set/#set-top-level-fields I tried:

await collection.updateOne({ _id: record._id }, { $set: { "Owed": due, "Yearly": assessed }});

This appears to work

  • Related