abdemirza
abdemirza

Reputation: 659

I am trying to add new values to key value pair in mongodb (mongoose) in nodejs

I have a schema with categories field :

categories{
  category_1 : [],
  category_2 : [],
  category_3 :[] ,
}

I am trying to push contestant's id in a particular category so after pushing id in category_1 ,it should be something like this:

categories{
  category_1 : [contestant_id],
  category_2 : [],
  category_3 :[] ,
}

These are the fields in an actual database .

{ "_id" : ObjectId("5ee7e804311aa55316e5b20a"), "tournament_id" : "[email protected]", "name" : "Updated Tournament", "event_date" : "2020-06-30", "last_entry" : "2020-06-29", "entry_fee" : 6000, "categories" : { "MU10" : [ ], "FU18" : [ ], "MU7" : [ ], "MU8" : [ ], "MSENIOR" : [ ], "FSENIOR" : [ ], "MU9" : [ ], "FU10" : [ ] }, "__v" : 0 }

Upvotes: 0

Views: 1344

Answers (3)

kuso.sama
kuso.sama

Reputation: 336

So, as I'm understanding right, you want to push contestant_id to categories.category_1, right?

To do this, just simply use

categories.category_1.push(contestant_id)

Upvotes: 0

Ana Lava
Ana Lava

Reputation: 787

You can do as below:

db.yourcollection.update(
   { _id: ObjectId("5ee7e804311aa55316e5b20a") },
   { $push: { "categories.MU10": "contestant_id" } }
)

Upvotes: 0

Lukas C
Lukas C

Reputation: 453

Use $push to append to Array:

For example to append contestant_id to the category_1 array:

db.TABLE.update(
   { _id: 1 },
   { $push: { category_1: contestant_id } }
)

Upvotes: 1

Related Questions