[英]Post data to Subdocument - Mongoose Express
After googling....谷歌搜索后......
Using Mongoose/Express to save data I have issues: Cannot post data to subdocument or nested document使用 Mongoose/Express 保存数据我有问题:无法将数据发布到子文档或嵌套文档
Here is my Mongoose model:这是我的 Mongoose model:
const Users = new Schema({
firstname : {
type : String
},
password : {type : String},
phone : {type : Number},
city : {type : String},
country : {type : String},
experience : [
{
title : {type : String},
company : {type : String},
description : {type : String},
date_bg : {type : Date},
date_end : {type : Date},
}
],
education : [
{
degree : {type : String},
school : {type : String},
description : {type : String},
date_bg : {type : Date},
date_end : {type : Date},
}
],
// ...
})
And here is post router:这是邮政路由器:
const addUser = async (req, res) => {
// my data from fronted is like this :
// req.body.experience is like this (same as education):
// [{title: "title experince 1", company: "title experince", date_bg: "2021-02-11", date_end: "2021-02-02", description: "title experince"}
{title: "title experince 2", company: "title experince 2", date_bg: "2021-02-10", date_end: "2021-02-08", description: "tstset"}]
const user = new Users(req.body) // This cause cast error for the *experience* and *education*
try {
await user.save()
return res.status(200).json({message : "Signin up successfully, Your account is now active!"})
} catch (error) {
return res.json({error : "Something went wrong, please try again later!", message : error})
}
}
My question is:我的问题是:
How to post my data to subdocument?如何将我的数据发布到子文档? (My problem is in the experience and education model)
(我的问题在于经验和教育模式)
in the req.body.experience of request there is a 1
before the second experience so change the format of body like this:在 request 的 req.body.experience 中,在第二次体验之前有一个
1
所以改变 body 的格式是这样的:
[
{
title: "title experince 1",
company: "title experince",
date_bg: "2021-02-11",
date_end: "2021-02-02",
description: "title experince"
},
{
title: "title experince 2",
company: "title experince 2",
date_bg: "2021-02-10",
date_end: "2021-02-08",
description: "tstset"
}
]
This is my recieve data but actually cannot saved:这是我收到的数据,但实际上无法保存:
{
email: 'manana04@gmail.com',
password: '$2a$10$DSpWahC5QCDEWwr1VljOXeok3awr/vVzDRcGazQsevu3H1ZgNY.pm',
firstname: 'dkfsdgk',
lastname: 'kvhdvgdjk',
job_title: 'cbhckvk5',
description: 'sdfvbilfgad',
hourly_rate: '454',
city: 'sdkvhdfvik',
country: 'hsvhdo',
education: [],
experience: [
{
title: 'Title experincev v',
company: 'dfvbhdfighfi',
date_bg: '2021-02-04',
date_end: '2021-02-17',
description: 'sdfsfsdfs'
},
{
title: 'tititititititititititititit',
company: 'dfldhkfjshdkfhsdkfshk',
date_bg: '2021-02-04',
date_end: '2021-02-16',
description: 'sdfshfdslfsdhfhs'
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.