0

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.

SantGT5
  • 53
  • 4
  • The request is overriding name and timer values. It should be an array, if you want to store multiple values. And when receiving an array, the controller should be updated to expect it. – Gregorio Palamà Sep 30 '21 at 20:20
  • My schema is array, but still isn't working.. and as you can see, my result is array of object. – SantGT5 Sep 30 '21 at 20:27

2 Answers2

1
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

viren
  • 113
  • 4
1

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);
Gregorio Palamà
  • 1,965
  • 2
  • 17
  • 22