简体   繁体   English

如何将 object 推送到 MongoDB 中另一个数组中的数组?

[英]How to push object to array which is in another array in MongoDB?

I have a Mongoose Schema:我有一个 Mongoose 模式:

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:但在 MongoDB 中,是这样的:

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?但我不知道如何指定该查询...我该怎么做?


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.位置 $ 运算符标识数组中要更新的元素,而无需显式指定数组中元素的 position。

Try it:试试吧:

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

You can try more here: LINK您可以在这里尝试更多: LINK

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM