Search code examples
expressmongoosemongoose-schemamongoose-populate

data association problem with nested route with Express.js


Suppose I want to have REST endpoints which look roughly like this:

/blogs
/blogs/new
/blogs/:id
/blogs/:id/edit
/blogs/:id/comments/new

CRUD on each if makes sense. For example, /blogs POST creates a new blog, GET fetches all blogs. /blogs/:id GET fetches just that one blog with associated comments. /blogs/:id/comments/ POST creates a new comment to that particular blog

Now everything work perfectly but the comment association with each blog not working correctly. I think my models or /blogs/:id/comments/new route create that error.
blogSchema

var blogSchema=new mongoose.Schema({
    title:String,
    image:String,
    body:{type:String, default:""},
    created:{ type: Date },
  comments:[{
    type:mongoose.Schema.Types.ObjectId,
    ref:'Comment'
  }]
});

commentSchema

var commentSchema=mongoose.Schema({
    text:String,
    author:String
})

all route related with comment

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);
                }
            })
        }
    })
})

finally /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})
        }
    })
})

Error:
image
I know that it's quite difficult to understand all those thing without working with it that's why I give my virtual environment where you will find my project and can manipulate it.Any kind of help will be appreciated.
Thanks for your time. Thanks in advance .


Solution

  • The req.body.comment is {title:'emon',body:'new comment'}. That's not fit with what defined in commentSchema. Change it to fit the structure of schema will solve the problem.