【发布时间】:2018-09-20 18:52:17
【问题描述】:
为 MERN 堆栈应用程序使用 express.js 框架。这是我的第一个js 全栈应用程序,对很多这些功能都很陌生。需要POST 一个主题的新帖子并更新主题。引用 Posts 集合的帖子。
这里是server.js:
router.post('/:id/posts', (req,res) => {
const { id } = req.params // works
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: id
})
const topic = Topic.findById(id).then(topics => res.json(topics))
console.log(topic.posts)
// and I don't understand why my topic object is always undefined I need to push a reference into it I think.
//need to save/update topic object to db
//need to save new post
//my other post function has newPost.save().then(post => res.json(post) and it works. but in this function it doesn't.
});
这是架构
const TopicSchema = new Schema({
topic: {
type: String,
required: true
},
description: {
type: String,
required: true
},
posts: [
{
type: Schema.Types.ObjectId,
ref: 'post'
}
],
date: {
type: Date,
default: Date.now
}
});
如果有人能告诉我我做错了什么,我将不胜感激。如果需要更多信息,也推送到GitHub
第 31 行是代码 sn-p。
【问题讨论】:
标签: javascript node.js express ecmascript-6 mern