5

Using Mongoose, How can I add more items to an object without replacing existing ones?

 User.findOneAndUpdate(
  { userId: 0 },
  { userObjects: { newItem: value } }
 );

The problem with above code is that it clears whatever was there before and replaces it with newItem when I wanted it just to add another item to userObjects(Like push function for javascript arrays).

omidh
  • 2,526
  • 2
  • 20
  • 37

3 Answers3

6

Use dot notation to specify the field to update/add particular fields in an embedded document.

User.findOneAndUpdate(
  { userId: 0 },
  { "userObjects.newerItem": newervalue } }
);

or

User.findOneAndUpdate(
  { userId: 0 },
  { "$set":{"userObjects.newerItem": newervalue } }
);

enter image description here

or Use $mergeObjects aggregation operator to update the existing obj by passing new objects

User.findOneAndUpdate(
  {"userId":0},
  [{"$set":{
    "userObjects":{
      "$mergeObjects":[
        "$userObjects",
        {"newerItem":"newervalue","newestItem":"newestvalue"}
      ]
    }
  }}]
)
s7vr
  • 73,656
  • 11
  • 106
  • 127
  • this will update data in `userObjects.newerItem`. in my case I need to append the data to the existing object. like `$post` using in array – sharun k k Nov 25 '20 at 11:31
  • That is not true. Please try it. This will update the object to `{“userObjects”: {“newItem”:”value”, “newerItem”:”newvalue”}}` - example here - https://mongoplayground.net/p/SRdoAn4LG9N – s7vr Nov 25 '20 at 13:38
  • Also added another aggregation based update option where you can pass the object itself without needing to list the each key value pair. – s7vr Nov 25 '20 at 14:08
1

According to your question, i am guessing userObjects is an array.

You can try $push to insert items into the array.

 User.findOneAndUpdate(
  { userId: 0 },
  { $push : {"userObjects": { newItem: value } }},
  {safe :true , upsert : true},function(err,model)
  {
      ...
  });

For more info, read MongoDB $push reference.

Hope it helps you. If you had provided the schema, i could have helped better.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52
1

Just create new collection called UserObjects and do something like this.

UserObject.Insert({ userId: 0, newItem: value }, function(err,newObject){

});

Whenever you want to get these user objects from a user then you can do it using monogoose's query population to populate parent objects with related data in other collections. If not, then your best bet is to just make the userObjects an array.

Corey Berigan
  • 614
  • 4
  • 14