0

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?

Kunok
  • 8,089
  • 8
  • 48
  • 89
  • db.collection('users').update( { _id: user.id, labels: [] }, { $set: { "labels.$" : resp.labels } } ) try with this – AB Udhay Sep 13 '16 at 10:37

4 Answers4

2
Try this:

db.collection('users').update(
          {"id":user.id},,
           {
             $push: {
               labels: {
                  $each: //yourArray
               }
             }
           }
        );
Shantanu Madane
  • 617
  • 5
  • 14
1

Try $set

db.collection('users').update(
      {"id":user.id},
      {$set:{"users.labels":"hola"}})
abdulbarik
  • 6,101
  • 5
  • 38
  • 59
1

$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 } } }
)
torryt
  • 150
  • 10
0

Try to include {upsert:true}:

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

Upsert inserts new value if it doesn't already exists.

Kunok
  • 8,089
  • 8
  • 48
  • 89
Samot
  • 103
  • 1
  • 7
  • However, there is an issue. It creates new attribute called users and inside that users object it creates labels object which includes labels. – Kunok Sep 13 '16 at 10:55