[英]Mongoose saving dynamic array of subdocuments in one shot
我搜索了高低,但没有找到解决方案。
我正在尝试保存一组子文档(即动态的)。
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
}
如果我对您的理解正确,您不应该解构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,
})),
});
您可以从请求正文中获取整个与会者数组并按原样保存,而不是对数组的一个 object 进行解构。
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 });
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.