Insert items into mongo array via mongoose Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Insert items into mongo array via mongoose without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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(…)”

Answer

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’);

We are here to answer your question about Insert items into mongo array via mongoose - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji