skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search