Kunok Kunok - 2 months ago 14
Node.js Question

Unable to push data into current object inside mongo database

I am using mongodb native and Node.js 6.5.0.

I have user object in mongodb which is structured as:

{
"_id" : ObjectId("57d7d294d96a73d128c46db9"),
"id" : "105862592064",
"labels" : [

]
}


I have a loop (for each user found) get data from API and then push it into object attribute of array type. Where user id
user.id
and data to push is
resp.labels
.

This is my code:

db.collection('users').update(
{"id":user.id},
{"$push":{"users.labels":resp.labels}}
)


It doesn't return any error, neither it does update objects. What have I done wrong?

Answer

$push is for pushing a single element to an array. Use $push together with $each to push multiple elements. Also, quotes around the object labels should not be neccessary:

db.collection('users').update(
      { id:user.id },
      { $push: { labels: { $each: resp.labels } } }
)