Mongoose how to insert an object inside an object that is inside an array

Viewed 46

I want to push an object inside an object that is inside an array. To make it clearer, here is the structure of what my mongoose model is like this:

username: {
        type: String,
        min: 1,
        required:true,
    },
    password: {
        type: String,
        required: true
    },
    folders:[
        {
            title:String, 
            files:[{
                fileID: String,  
                type: String
            }]
        }
    ]

each folder would automatically get an object id. What I want to do is to add an object to the specific folder's files. The files is an array which is where I would push the object. I tried adding it using something like this:

await User.findOne({username:username}, {$push: 
                    {[folderID.files]: [ {title:'title',  type:'type'} ]}
                })

but it doesn't work

1 Answers

You can find the folder that need update by id then use $push and $ operator to push your new file to files array of that folder:

await User.findOneAndUpdate(
  { username: username, "folders._id": folderID }, 
  { $push: { "folders.$.files": {title:'title',  type:'type'} }}
)
Related