一键保存猫鼬动态数组子文档

时间:2020-06-23 15:20:25

标签: arrays mongodb mongoose

我搜索过很多,但没有找到解决方法。

我正在尝试保存一系列子文档(动态的)。

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

当前我只能在数组中保存1个元素。

数组中的项目始终是不同的。

我没有选择先创建“事件”然后再添加“与会者”的选项。

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
}

2 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,则不应破坏attendee并将其插入每个新的Event参与者中(选择要在数据库中插入哪个键)。

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

答案 1 :(得分:0)

您可以从请求正文中获取整个参与者数组并将其保存为原样,而不是破坏数组的一个对象。

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