【发布时间】:2019-08-14 23:58:04
【问题描述】:
我有一个博客模型,它有多个 cmet,有多个回复。我想浏览所有这些,而我的代码只能访问前 2 层。
这是在我的数据库中作为评论对象:
{ "_id" : ObjectId("5c9770fc0147e40f1c53aab8"), "comments" : [ ObjectId("5c97734db48ab60f6139ffa3") ], "author" : ObjectId("5c9770e60147e40f1c53aab5"), "text" : "comment", "__v" : 1 }
{ "_id" : ObjectId("5c97734db48ab60f6139ffa3"), "comments" : [ ObjectId("5c977a169f98a8106dc0dc5c") ], "text" : "2", "__v" : 1 }
{ "_id" : ObjectId("5c977a169f98a8106dc0dc5c"), "comments" : [ ], "text" : "3", "__v" : 0 }
{ "_id" : ObjectId("5c977b3b3a5bb410ce7e0e70"), "comments" : [ ObjectId("5c977b533a5bb410ce7e0e71") ], "author" : ObjectId("5c9770e60147e40f1c53aab5"), "text" : "1", "__v" : 1 }
{ "_id" : ObjectId("5c977b533a5bb410ce7e0e71"), "comments" : [ ObjectId("5c977b6f3a5bb410ce7e0e73") ], "author" : ObjectId("5c9770e60147e40f1c53aab5"), "text" : "2", "__v" : 1 }
{ "_id" : ObjectId("5c977b6f3a5bb410ce7e0e73"), "comments" : [ ], "author" : ObjectId("5c9770e60147e40f1c53aab5"), "text" : "3", "__v" : 0 }
评论架构:
var commentSchema = new mongoose.Schema({
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
text: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}]
});
博客对象:
{ "_id" : ObjectId("5c9770ee0147e40f1c53aab6"), "comments" : [ ObjectId("5c9770fc0147e40f1c53aab8"), ObjectId("5c977b3b3a5bb410ce7e0e70") ], "title" : "title", "image" : "", "text" : "text", "author" : ObjectId("5c9770e60147e40f1c53aab5"), "date" : ISODate("2019-03-24T11:58:38.227Z"), "__v" : 2 }
博客架构:
var blogSchema = new mongoose.Schema({
title: String,
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
date: ({type: Date, default: Date.now}),
text: String,
image: String,
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}]
})
这是我的路线
router.get("/:id",function(req,res){
Blog.findById(req.params.id)
.populate("author")
.populate({
path: "comments",
model: "Comment",
populate: {
path: "comments",
model: "Comment"
}
})
.exec(function(err,blog){
if (err) console.log(err);
res.render("../views/blogs/show",{blog: blog});
})
});
这是我在打印博客时得到的:
{ comments: [ { comments: [Array], _id: 5c97734db48ab60f6139ffa3, text: '2', __v: 1 } ], _id: 5c9770fc0147e40f1c53aab8, author: 5c9770e60147e40f1c53aab5, text: 'comment', __v: 1 },{ comments: [ { comments: [Array], _id: 5c977b533a5bb410ce7e0e71, author: 5c9770e60147e40f1c53aab5, text: '2', __v: 1 } ], _id: 5c977b3b3a5bb410ce7e0e70, author: 5c9770e60147e40f1c53aab5, text: '1', __v: 1 }
如何填充评论对象的所有嵌套数组?
【问题讨论】: