【问题标题】:Insert items into mongo array via mongoose通过 mongoose 将项目插入 mongo 数组
【发布时间】:2022-01-07 07:22:19
【问题描述】:

我有一个类似下面代码的 mongo 集合:

const ExerciseSchema = new Schema({
  name: { type: String, required: true },
  exercise: [
    {
      exerciseId: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: Exercise,
      },
      period: { type: String, enum: ["day", "night"], required: true },
    },
  ],
  timestamp: { type: Date, default: Date.now() },
});

当我尝试同时插入多个练习时,考虑到我的练习是一个数组,mongo 只保存第一个寄存器。例如,我尝试插入:

{
    "name": "Exercise 1",
    "exercise": [
        {
            "exerciseId": "1",
            "period": "night"
        },
        {
            "exerciseId": "1",
            "period": "day"
        }
    ]
}

而且,保存后,get方法返回我:

[
    {
        "timestamp": "2021-11-30T14:18:42.455Z",
        "_id": "1",
        "name": "Exercise 1",
        "exercise": [
            {
                "exerciseId": "1",
                "period": "night",
            }
        ],
        "__v": 0
    }
]

也就是说,猫鼬只保存了我数组中的第一个寄存器。 有人知道为什么会这样吗? 从控制器听到我的创建方法:

exports.create = (req, res) => {
  const {
    name,
    exercise: [{ exerciseId, period }],
  } = req.body;
  const newExercise = new Exercise({
    name,
    exercise: [{ exerciseId, period }],
  });
  newExercise.save((err, data) => {
    if (err) {
      res.status(500).send({ message: err });
      return;
    }
    res
      .status(200)
      .send({
        message: "Success",
      });
  });
};

Obs:我通过“new Exercise(...)”从控制器中引用我的 ExerciseSchema

【问题讨论】:

    标签: node.js mongodb mongoose schema


    【解决方案1】:

    用它来更新数组:

    parent ---> a mongooose doc
    parent.child.push({new child object});
    parent.markModified('child');
    parent.save();
    

    在您的情况下,孩子是运动数组,并且在 parent.markModified('child');你必须把 parent.markModified('exercise');

    【讨论】:

    • 我正在尝试使用:``` newExercise.exercise.push(req.body.exercise) newExercise.markModified('exercise') ``` 但它还没有工作。 ..
    • 你能在保存之前附上一个console.log的newExercise const吗?
    • 跟随控制台:``` { timestamp: 2021-11-30T16:54:26.622Z, _id: 1, name: 'Exercise 1', exercise: [ { exerciseId: 1, period: '夜晚' }, {} ] } ```
    • 我的 req.body.exercise: ``` [ { exerciseId: '1', period: 'night' }, { exerciseId: '2', period: 'day' } ] ```
    • 和你的 const 锻炼从身体中取出?,如果一切正常,尝试像这样推动:req.body.exercise.map(exercise => { newExercise.exrcise.pus(exercise)}。推动每身体元素
    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多