首页 > 解决方案 > 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})
        }
    })
})

错误:我知道如果不使用它很难理解所有这些东西,这就是为什么我提供我的虚拟环境,您可以在其中找到我的项目并可以操作它。任何形式的帮助将不胜感激。谢谢你的时间。提前致谢 。
图片

标签: expressmongoosemongoose-schemamongoose-populate

解决方案


req.body.comment{title:'emon',body:'new comment'}。_ 这不符合commentSchema. 改变它以适应模式的结构将解决问题。


推荐阅读