SantGT5
SantGT5

Reputation: 63

Can't create multiple values in mongo - Array of Objects

I'm trying to save multiple values on mongoDB in meetings field, this is my Schema:

const MeetingSchema = new mongoose.Schema({
  meetings: [
    {
      name: { type: String, require: true, trim: true },
      timer: { type: Number, require: true, trim: true },
    },
  ],
  date: { type: Date, default: Date.now, trim: true },
  responsible: { type: String, require: true, trim: true },
});

My controller:

const { name, timer } = req.body;
      const response = await MeetingModel.create({
        meetings:
          {
            name: name,
            timer: timer,
          },
 
      });

return res.status(201).json(response);

This is the body of my request that I did on Insomnia:

{
    "name": "Meeting Name",
    "timer": 100,

    "name": "Meeting Name2",
    "timer": 400
}

Result:

{
  "meetings": [
    {
      "name": "Meeting Name2",
      "timer": 400,
      "_id": "615618effd96b823d2cf741b"
    }
  ],
  "_id": "615618effd96b823d2cf741a",
  "date": "2021-09-30T20:07:11.344Z",
  "__v": 0
}

Only my last data is saving as you can see, what I'm trying is save multiple data in meetings, not just the last one.

Upvotes: 0

Views: 303

Answers (2)

Gregorio Palamà
Gregorio Palamà

Reputation: 1952

The request you are sending

{
    "name": "Meeting Name",
    "timer": 100,

    "name": "Meeting Name2",
    "timer": 400
}

rewrites the value for name and timer. It should be an array of objects, not an object itself, even less should rewrite the values. To obtain your desired behaviour, the request should look like this:

[
    {
        "name": "Meeting Name",
        "timer": 100
    },
    {
        "name": "Meeting Name2",
        "timer": 400
    }
]

This way, you'll also need to change your controller. It should iterate through the array, so the code will be like this:

req.body.forEach(item => {
      const response = await MeetingModel.create({
        meetings:
          {
            name: item.name,
            timer: item.timer,
          },
 
      });
});

return res.status(201).json(response);

Upvotes: 1

viren
viren

Reputation: 111

const { name, timer } = req.body;
  const response = await MeetingModel.create({
   $push{ 
     meetings:
      {
        name: name,
        timer: timer,
      }
    }

  });

 return res.status(201).json(response);

As you are updating an array you need to add the $push to add and $pull to delete Ref: More Info

Upvotes: 1

Related Questions