简体   繁体   中英

Mongoose saving dynamic array of subdocuments in one shot

I have searched high and low but haven't found a solution.

I am trying to save an array of subdocuments (that is dynamic).

Here's my schema:

    const EventSchema = new Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'users'
  },
  title: {
    type: String,
    required: true
  },
  attendee:[ 
    {
      email: {
        type: String,
        required: true
      },
      name: {
        type: String,
        required: true
      },
      status: {
        type: String
      }
    }]
});

Here's the route:

router.post('/', auth, async (req, res) => {
  const {title, attendee: [{ email, name, status }] } = req.body

  try{  
    const newEvent = new Event({
        title,
        user: req.user.id,
        attendee: [{ email, name, status }]
    });

    const event = await newEvent.save();
    if (!event) throw Error('Something went wrong saving the event');

    res.status(200).json(event);

   
  catch (e) {
  res.status(400).json({ msg: e.message });
}
});

Currently I am only getting 1 element in the array to save.

The items in the array will always be different.

I don't have the option of creating the "event" first and then adding "attendees".

Example of input:

{
    "title": "Something",
    "attendee": [
      {
        "email": "email@gmail.com",
        "name": "Bob"
      },
             {
        "email": "sandwich@gmail.com",
        "name": "Martha"
      }
    ]
  }

Output:

{
  "_id": "5ef1521f06a67811f74ba905",
  "title": "Something",
  "user": "5ecdaf3601cd345ddb73748b",
  "attendee": [
    {
      "_id": "5ef1521f06a67811f74ba906",
      "email": "email@gmail.com",
      "name": "Bob"
    }
  ],
  "__v": 0
}

If I understand you correctly, you should not destructure attendee and insert into your new Event every attendee (choosing which key to insert in database).

const {
  title,
  attendee,
} = req.body;

const newEvent = new Event({
  title,
  user: req.user.id,

  attendee: attendee.map(x => ({
    email: x.email,
    name: x.name,
    status: x.status,
  })),
});

Instead of destructuring for the one object of the array, you can get the whole array of attendee from the request body and save it as it is.

router.post('/', auth, async (req, res) => {
  
  const eventObj =  {
  user: req.user.id,
  title : req.body.title, 
  // get the whole array of attendee objects from the request
  attendee: req.body.attendee 
  } 

  try{  
    const newEvent = new Event(eventObj);

    const event = await newEvent.save();
    if (!event) throw Error('Something went wrong saving the event');

    res.status(200).json(event);

   
  catch (e) {
  res.status(400).json({ msg: e.message });
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM