【发布时间】:2020-06-26 05:47:19
【问题描述】:
我搜索了高低,但没有找到解决方案。
我正在尝试保存一组子文档(即动态的)。
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
}
【问题讨论】: