我有一个用户模型,并尝试将education字段作为json对象添加到mongoDB中,如下所示,
用户模型
education: {
"school": String,
"years":Number
},
客户
//add Education section
const updateEducation = async (e) => {
e.preventDefault();
await fetch(`http://localhost:5000/api/user/updateEducation`, {
method: "PUT",
headers: { "Content-Type": "application/JSON", token: accessToken },
body: JSON.stringify({ userid: userid, educationSchool: educationSchool,
educationYearText: EducationYear}),
})
.then((res) => res.json())
.then((data) => {
console.log("User education is:", data.education +""+data.educationYear);
});
};
服务器
const updateEducation = async (req, res) => {
try {
const user = await User.findOneAndUpdate(
{ _id: req.body.userid },
{
$set: {
'education.school': req.body.educationSchool,
'education.years': req.body.educationYearText,
},
}
);
if (!user) {
res.status(404).json("user not exist");
}
res
.status(200)
.json({
education: user.education.School,
educationYear: user.education.years,
});
} catch (error) {
res.status(500).send({ error: error.message });
}
};
当即时消息在postmanhttp://localhost:5000/api/user/updateEducation中命中此端点时
{
"userid":"63bbe4df75dca5aac7576e47",
"educationSchool":"Test college",
"educationYearText":"2018"
}
我得到 {"错误":"findAndModify期间计划执行器错误::原因:无法在元素{education:}中创建字段"school"[]}"}
怎么了?
1条答案
按热度按时间gwo2fgha1#
您应该将
$push
放入一个数组: