Alper Berber
Alper Berber

Reputation: 71

Updating an array of objects iteratively in mongodb nodejs

I am trying to update a couple of objects in the MongoDB in nodejs. Here's the problem I'm having:
I have an array of objects kind of looks like this:

[{
   "_id": {
        "$oid": "5ed611265828aa77c978afb4"
    },
    "advert_id": "5ec2e4a8bda562e21b8c5052",
    "isCategory": false,
    "name": "2+1 Ev Taşıma",
    "value": "2200 TL"
},
{
    "_id": "40", // this object is recently added so it doesn't 
                // have an oid it needs to be inserted instead of updating.
    "advert_id": "5ec2e4a8bda562e21b8c5052",
    "isCategory": false,
    "name": "4+1 Ev Taşıma",
    "value": "7000 TL"
},
]

I'm trying to update every one of these objects using collection.updateMany with upsert: true Here's the code I wrote:

mongodb.collection('prices').updateMany({}, {$set: post.prices}, {upsert: true}, (error, result) => {
    if(error) throw error;
    res.json(response);
})

Here's the error:

MongoError: Modifiers operate on fields but we found type array instead. For example: {$mod: {<field>: ...}} not 
{$set: [ { _id: "5ed611265828aa77c978afb4", advert_id: "5ec2e4a8bda562e21b8c5052", isCategory: false, name: "2+1 
Ev Taşıma", value: "2000 TL", isVisible: false } ]}

The problem seems that I'm trying to pass prices array directly into the $set pipe. What's a field type and how can I translate my array into that.

Appreciate the help, had some difficult time searching through the documentation but couldn't find any related chapter. I can really appreciate it if you can also link the documentation's related part in your answer.

Database document:

{
    "_id": {
        "$oid": "5ed611265828aa77c978afb4"
    },
    "advert_id": "5ec2e4a8bda562e21b8c5052",
    "isCategory": false,
    "name": "2+1 Ev Taşıma",
    "value": "2000 TL",
    "isVisible": false
}

Upvotes: 1

Views: 3957

Answers (1)

Gibbs
Gibbs

Reputation: 22964

I see a problem here {$set: post.prices}

It should be {$set: {'prices':post.prices}} - You should provide a document to $set

Refer

    db.col.find({
  '_id.$oid': '5ed611265828aa77c978afb4'
},
{
  $set: {
    "advert_id": "5ec2e4a8bda562e21b8c5052",
    "isCategory": false
  },
  {
    upsert: true
  }
}

Upvotes: 4

Related Questions