首页 > 解决方案 > mongodb插入对象数组

问题描述

我需要通过 id 找到元素,然后进入对象数组,通过 id 找到所需的元素并将字段guessId 添加到其中,并将 id 键插入其中并分配 id 数组。我怎样才能做到这一点 ?

https://jsoneditoronline.org/?id=442f1dae0b2d4997ac69d44614e55aa6

一般来说,我需要创建一个具有这种结构的 GuessId 字段

在此处输入图像描述

其实我在做投票,就是guessId里面的key是go to vote,给它的数组,这个就是投票的用户

在此处输入图像描述

{
  "_id": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
  "bio": {
    "firstname": "Лена",
    "lastname": "фыв",
    "middlename": "",
    "company": "вв"
  },
  "files": [
    {
      "_id": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6",
      "destination": "./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
      "filename": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
      "path": "uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
      "folder": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
      "info": {
        "size": 20805727,
        "mimetype": "audio/mp3",
        "encoding": "7bit",
        "originalname": "Ахуевший Ленусик (Банк русский стандарт). Выпуск #5..mp3",
        "fieldname": "selectedFile"
      },
      "userId": "5e05da745b21e61ccc84a892",
      "date": "2019-12-27T10:19:12.213Z"
    },
    {
      "_id": "81b94dea-ece6-421c-b68a-0aa59332cd0d",
      "destination": "./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
      "filename": "81b94dea-ece6-421c-b68a-0aa59332cd0d.mp3",
      "path": "uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\81b94dea-ece6-421c-b68a-0aa59332cd0d.mp3",
      "folder": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
      "info": {
        "size": 13515683,
        "mimetype": "audio/mp3",
        "encoding": "7bit",
        "originalname": "Выпуск #75 Попрошайка НСВ..mp3",
        "fieldname": "selectedFile"
      },
      "userId": "5e05da745b21e61ccc84a892",
      "date": "2019-12-27T10:25:37.710Z"
    }
  ],
  "date": "2019-12-27T10:19:12.213Z",
  "__v": 1
}

架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const HabalkaSchema = new Schema({
  _id: {
    type: String
  },
  bio: {
    firstname: String,
    lastname: String,
    middlename: String,
    company: String
  },
  files: [
    {
      _id: {
        type: String
      },
      destination: {
        type: String
      },
      filename: {
        type: String
      },
      path: {
        type: String
      },
      folder: {
        type: String
      },
      info: {
        size: {
          type: Number
        },
        mimetype: {
          type: String
        },
        encoding: {
          type: String
        },
        originalname: {
          type: String
        },
        fieldname: {
          type: String
        },
      },
      date: {
        type: Date,
        default: Date.now
      },
      bio: {
        type: Object
      },
      userId: String,
      guessId: {},
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }
});
module.exports = Habalka = mongoose.model('habalka', HabalkaSchema);

标签: node.jsmongodbexpressmongoose

解决方案


您可以像这样使用位置$运算符:

router.put("/habalka/:id/:fileId/:guessId", async (req, res) => {

  const result = await Habalka.findOneAndUpdate(
    {
      _id: req.params.id,
      "files._id": req.params.fileId
    },
    {
      "files.$.guessId": {
        [req.params.guessId]: ["a", "b"] //todo: get this array from req.body
      }
    },
    {
      new: true
    }
  );

  res.send(result);
});

路线网址: http://..../habalka/f58482b1-ae3a-4d8a-b53b-ede80fe1e225/2e4e40c7-4df6-4974-8d16-bb24cd8134d6/asda2

这将在给定文件中为您提供如下结果:

    "files": [
        {
            "info": {
                "size": 20805727,
                "mimetype": "audio/mp3",
                "encoding": "7bit",
                "originalname": "Ахуевший Ленусик (Банк русский стандарт). Выпуск #5..mp3",
                "fieldname": "selectedFile"
            },
            "date": "2019-12-27T10:19:12.213Z",
            "_id": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6",
            "destination": "./uploads/f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
            "filename": "2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
            "path": "uploads\\f58482b1-ae3a-4d8a-b53b-ede80fe1e225\\2e4e40c7-4df6-4974-8d16-bb24cd8134d6.mp3",
            "folder": "f58482b1-ae3a-4d8a-b53b-ede80fe1e225",
            "userId": "5e05da745b21e61ccc84a892",
            "guessId": {
                "asda2": [
                    "a",
                    "b"
                ]
            }
        },

稍后,如果您想在其中一个guessId 数组中添加一项,可以使用以下代码:

router.put("/habalka/:id/:fileId/:guessId", async (req, res) => {
  const result = await Habalka.findOneAndUpdate(
    {
      _id: req.params.id,
      "files._id": req.params.fileId
    },
    { $push: { [`files.$.guessId.${req.params.guessId}`]: "c" } },
    {
      new: true
    }
  );

  res.send(result);
});

推荐阅读