Home > Enterprise >  Adding element inside nested array in mongoose
Adding element inside nested array in mongoose

Time:12-27

Server Started at Port 3000...
{
  _id: new ObjectId("61c707e9f4ff040a47d27c3f"),
  username: 'adityaaryam',
  password: '1234',
  nameOfUser: 'Aditya Aryam',
  emailOfUser: '[email protected]',
  userAllLists: [
    {
      name: 'Hello',
      items: [],
      _id: new ObjectId("61c70d915448262d1dca1a69")
    },
    {
      name: 'Work',
      items: [],
      _id: new ObjectId("61c70d965448262d1dca1a70")
    },
    {
      name: 'Home Work',
      items: [],
      _id: new ObjectId("61c70d9b5448262d1dca1a79")
    },
    {
      name: 'Hello',
      items: [],
      _id: new ObjectId("61c70e7f5448262d1dca1a84")
    },
    {
      name: 'Play',
      items: [],
      _id: new ObjectId("61c7126a5448262d1dca1a9b")
    },
    {
      name: 'Eat',
      items: [],
      _id: new ObjectId("61c71325b0219e6ce4f57990")
    },
    {
      name: 'Walla',
      items: [],
      _id: new ObjectId("61c7197de9564390d506cbe9")
    }
  ],
  __v: 7
}

This is how my database looks like. I want to push new elements to "items" array which is nested inside the "userAllLists" array using mongoose. How do I implement this?

I have been trying findOneAndUpdate using $push but I am not able to achieve my desriable results.

My Schemas are as follows:

const itemSchema = {
    name: String
};

const customListSchema ={
    name:String,
    items:[itemSchema]
};

const userSchema={
    username: String,
    password: String,
    nameOfUser: String,
    emailOfUser: String,
    userAllLists:  [customListSchema],
};

Thanks in Advance!

CodePudding user response:

I think $push is the right way to push new elements to nested arrays, you didn't show the code you tried to see if it works or not, at all here is an example based on your schema

User.update({_id: "61c707e9f4ff040a47d27c3f", }, {
  '$push': {
     "userAllLists.$[].items": {name: "test item name"}
  }
});

Note: $[] expressions will push the specified object inside all items arrays that exist in userAllLists

To push the item for only specific userAllLists object you can use the following syntax

User.update({_id: "61c707e9f4ff040a47d27c3f", "usersAllLists._id": "61c70d915448262d1dca1a69"}, {
  '$push': {
     "userAllLists.$.items": {name: "test item name"}
  }
});

this will ensure to push the item object to the specified usersAllLists object which has this id 61c70d915448262d1dca1a69

  • Related