如何解决如何将对象添加到作为对象内键值的数组中?
我有一个这样的用户模型:
const userSchema = new mongoose.Schema({
name: {
type: String,required: true
},courses: {
type: Object,required: true
}
})
还有这样的课程模型:
const courseSchema = new mongoose.Schema({
course_code: {
type: String,course_title: {
type: String,required: true
}
})
app.js文件在这里:
app.post('/enroll/:id',async function (req,res) {
const courseWithID = await Course.findById(req.params.id)
const course = {"course_code": courseWithID.course_code,"course_title": courseWithID.course_title}
const userID = req.user.id
await User.findByIdAndUpdate(userID,{"courses": course},{new: true,runValidators: true,useFindAndModify: false})
res.redirect('/dashboard')
})
第一次执行app.js之后,我得到以下结果:
{
"name": "Person","courses": {
"course_code": "123","course_title": "ABC"
}
}
第二次执行app.js之后,我得到以下结果:
{
"name": "Person","courses": {
"course_code": "456","course_title": "DEF"
}
}
但是在第二次执行app.js之后,我想要这个结果:
{
"name": "Person","courses": [
{
"course_code": "123","course_title": "ABC"
},{
"course_code": "456","course_title": "DEF"
}
]
}
我该怎么做?
解决方法
快速修复,
- 将
courses
类型Object
更改为Array
const userSchema = new mongoose.Schema({
name: {
type: String,required: true
},courses: {
type: Array,required: true
}
})
- 在
courses
之前添加https://github.com/graphql/express-graphql,因为我们需要将对象推入数组
const courseWithID = await Course.findById(req.params.id);
const course = {
"course_code": courseWithID.course_code,"course_title": courseWithID.course_title
};
const userID = req.user.id;
await User.findByIdAndUpdate(userID,{
"$push": { "courses": course }
},{new: true,runValidators: true,useFindAndModify: false}
)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。