通过 mongoose 将项目插入 mongo 数组

Insert items into mongo array via mongoose

我有一个 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"
        }
    ]
}

并且,在保存之后,获取方法 returns 我:

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

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

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

用它来更新数组:

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

在你的例子中 child 是练习数组,在 parent.markModified('child');你必须把 parent.markModified('exercise');