Home > Net >  How to push object to array which is in another array in MongoDB?
How to push object to array which is in another array in MongoDB?

Time:01-08

I have a Mongoose Schema:

const UserSchema = new mongoose.Schema({
  mail: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  folders: [
    {
      folderName: {
        type: String,
        default: 'Main',
        required: true,
      },
      files: [
        {
          fileName: String,
          fileType: String,
          date: String,
          filePath: String,
        }
      ]
    }
  ]
});

For this scheme, I would like to get the user's mail and the name of the folder from the request and add the file data to this folder, but I don't know how to push file to correct folder.

I want to do this code:

const mail = req.body.mail;
const folderName = req.body.folderName;
const file = {
    fileName: 'file222',
    fileType: '.png',
    date: '13-02-2022 21:15',
    filePath: '/uploads',
  }

const user = await userModel.findOne({ mail: mail });
const folders = user.folders.filter(folder => folder.folderName === folderName);
folders[0].files.push(file);

but in MongoDB, something like this:

const userFile = await userModel.updateOne(
    { mail: mail, "folders.folderName": folderName },
    {
      $push: {
        folders: {
          files: file
        }
      }
    }
  );

But I don't know how to specify that query... how can I supposed to do it?

CodePudding user response:


const userFile = await userModel.updateOne(
    { mail: mail, "folders.folderName": folderName },
    {
      $push: {
        folders.$.files: file
      }
    }
  );

Docs

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

CodePudding user response:

Try it :

const userFile = await userModel.updateOne(
    { mail: mail, "folders.folderName": folderName },
    {
      $push: {
        "folders.$.files":file
      }
    }
  );

You can try more here: LINK

  • Related