Home > front end >  Insert items into mongo array via mongoose
Insert items into mongo array via mongoose

Time:12-01

I have a mongo collection like the code below:

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() },
});

When I try to insert multiple exercises at the same time, considering that my exercises are an array, the mongo saves just the first register. For instance, I try to insert:

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

And, after saving it, the get method returns me:

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

That is, the mongoose saves just the first register in my array. Does anyone know why it is happening? Hear it my create method from the controller:

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: I'm referring to my ExerciseSchema from the controller by "new Exercise(...)"

CodePudding user response:

use it to update arrays:

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

in your case child is exercise array and in parent.markModified('child'); you have to put parent.markModified('exercise');

  • Related