博客模型:
ar schema_blog=new mongoose.Schema({
owner:{
type:mongoose.Schema.Types.ObjectId,
ref:"User"
},
title:String,
image:String,
description:String,
created:{type: Date, default: Date.now},
likes: Number,
dislikes: Number,
comments:[{
type:mongoose.Schema.Types.ObjectId,
ref:Comment,
}]
});
var Blog=mongoose.model("blog",schema_blog);
module.exports=Blog;
评论模型:
var schema_comment=new mongoose.Schema({
text:String,
created:{type: Date, default: Date.now},
author:{
type:mongoose.Schema.Types.ObjectId,
ref:"User"
},
authorName:String
});
当我尝试在博客中填充评论时,我得到一个空对象。 ID是正确的。我不明白问题是什么。
var Comment=mongoose.model("comment",schema_comment);
Blog.findById(id).populate("comments").exec((err,b)=>{
console.log(b);
})
请有人解决问题。
答案 0 :(得分:1)
更新
ref
必须为String,您传递了未定义的变量。
var schema_blog = new mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
title: String,
image: String,
description: String,
created: {
type: Date,
default: Date.now
},
likes: Number,
dislikes: Number,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "comment", //This must be String
}]
});
module.exports = mongoose.model("blog", schema_blog);
填充comments
Blog.findById(req.params.id)
.populate("comments")
.exec(function(err, blogs) {
if (err) {
console.log(err);
} else {
res.render("blogs/show", {
blog
});
}
});