【发布时间】:2020-01-22 09:10:38
【问题描述】:
假设我想拥有大致如下所示的 REST 端点:
/blogs
/blogs/new
/blogs/:id
/blogs/:id/edit
/blogs/:id/comments/new
每个 if 的 CRUD 都是有意义的。例如,/blogs POST 创建一个新博客,GET 获取所有博客。 /blogs/:id GET 只获取具有相关 cmets 的一个博客。 /blogs/:id/cmets/ POST 为该特定博客创建新评论
现在一切正常,但与每个博客的评论关联无法正常工作。我认为我的模型或 /blogs/:id/cmets/new 路线会产生该错误。
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
})
与评论相关的所有路线
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})
}
})
})
错误:
我知道如果不使用它就很难理解所有这些东西,这就是为什么我给我的虚拟environment 在那里你可以找到我的项目并可以操作它。任何形式的帮助将不胜感激。
感谢您的宝贵时间。
提前致谢。
【问题讨论】:
-
错误是什么?
-
@CuongLeNgoc 先生,我更新了我的问题。看看当我从 /blogs/:id/cmets/new 添加新评论时,它没有填充博客,而是显示空文本和作者。如果您需要更多信息,请发表评论。再次感谢
-
也许将
blog.comments.push(comment);更改为blog.comments.push(comment._id);会有所帮助。 -
让我检查一下@CuongLeNgoc 先生
-
@CuongLeNgoc 先生同样的问题。显示空文本和作者 :)
标签: express mongoose mongoose-schema mongoose-populate