express - Express.js 嵌套路由的数据关联问题
问题描述
假设我想拥有大致如下所示的 REST 端点:
/blogs
/blogs/new
/blogs/:id
/blogs/:id/edit
/blogs/:id/comments/new
CRUD 对每个 if 有意义。例如,/blogs POST 创建一个新博客,GET 获取所有博客。/blogs/:id GET 只获取一个带有相关评论的博客。/blogs/:id/comments/ POST 为该特定博客创建新评论
现在一切正常,但与每个博客的评论关联无法正常工作。我认为我的模型或 /blogs/:id/comments/new 路线会产生该错误。
博客架构
var blogSchema=new mongoose.Schema({
title:String,
image:String,
body:{type:String, default:""},
created:{ type: Date },
comments:[{
type:mongoose.Schema.Types.ObjectId,
ref:'Comment'
}]
});
评论模式
var commentSchema=mongoose.Schema({
text:String,
author:String
})
与评论相关的所有路线
app.get('/blogs/:id/comments/new',function(req,res){
//find blog by id
Blog.findById(req.params.id,function(err,blog){
if(err){
console.log(err)
}else{
res.render('comments/new.ejs',{blog:blog})
}
})
})
app.post('/blogs/:id/comments',function(req,res){
//lookup blog using id
Blog.findById(req.params.id,function(err,blog){
if(err){
console.log(err)
}else{
Comment.create(req.body.comment,function(err,comment){
if(err){
console.log(err)
}else{
blog.comments.push(comment);
blog.save()
res.redirect('/blogs/'+blog._id);
}
})
}
})
})
最后 /blogs/:id
app.get('/blogs/:id',function(req,res){
Blog.findById(req.params.id).populate('comments').exec(function(err,foundBlog){
if(err){
console.log(err)
res.redirect('/blogs')
}else{
res.render('blogs/show.ejs',{blog:foundBlog})
}
})
})
错误:我知道如果不使用它很难理解所有这些东西,这就是为什么我提供我的虚拟环境,您可以在其中找到我的项目并可以操作它。任何形式的帮助将不胜感激。谢谢你的时间。提前致谢 。
解决方案
req.body.comment
是{title:'emon',body:'new comment'}
。_ 这不符合commentSchema
. 改变它以适应模式的结构将解决问题。
推荐阅读
- amazon-web-services - 使用模式匹配的自定义错误状态代码不起作用
- c++ - 将函数指针指向成员方法
- javascript - 未捕获的类型错误:无法使用 Gatsby 和 graphQl 读取未定义的属性“数据”
- webgl - Tensorflow.js:连接张量时 WebGL 上下文丢失
- java - 在当前线程中创建 webdriver 后等待 Selenium 测试
- sql-server - 将 5.3M 记录插入临时表需要很长时间
- excel - 简单的 workbooks.open 代码导致 1004 错误
- java - 在没有任何导入的队列中搜索对象
- javascript - Javascript获取具有一类二的所有元素
- c# - 在尝试生成大量以 mysql 数据库的内容作为源的组合框时遇到问题