【发布时间】:2016-04-27 10:22:53
【问题描述】:
我有以下邮寄和收藏文件:
// posts
{
"_id" : ObjectId("56978d8cdbc511a81e7e2ea8"),
"body" : "Post body 1",
"created_at" : 1452772748737
},
{
"_id" : ObjectId("56978d3cdbc655b81e7e2e10"),
"body" : "Post body 2",
"created_at" : 1452772759731
}
// comments
{
"_post" : ObjectId("56978d8cdbc511a81e7e2ea8"),
"body" : "Comment 1"
},
{
"_post" : ObjectId("56978d3cdbc655b81e7e2e10"),
"body" : "Comment 2"
}
我需要查询所有包含所有cmets的帖子得到以下结果:
{
"_id" : ObjectId("56978d8cdbc511a81e7e2ea8"),
"body" : "Post body 1",
"created_at" : 1452772748737,
"comments": [{
"_post" : ObjectId("56978d8cdbc511a81e7e2ea8"),
"body" : "Comment 1"
}]
},
{
"_id" : ObjectId("56978d3cdbc655b81e7e2e10"),
"body" : "Post body 2",
"created_at" : 1452772759731,
"comments": [{
"_post" : ObjectId("56978d3cdbc655b81e7e2e10"),
"body" : "Comment 2"
}]
}
我的帖子和收藏架构如下所示:
// post
var PostSchema = mongoose.Schema({
},{
strict: "throw",
collection: "posts"
});
PostSchema.add({
created_at: {
type: Number,
'default': Date.now
}
});
PostSchema.add({
title: {
type: String
}
});
PostSchema.add({
body: {
type: String
}
});
// comment
var CommentSchema = mongoose.Schema({
},{
strict: "throw",
collection: "comments"
});
CommentSchema.add({
_post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});
CommentSchema.add({
body: {
type: String
}
});
获得上述结果的有效方法是什么?
【问题讨论】:
-
看看这里:seanhess.github.io/2012/02/01/mongodb_relational.html。为什么要将帖子和 cmets 分成 2 个集合?
-
你能显示为 post 和 cmets 定义的模型吗?
-
@NaeemShaikh 我更新了我的帖子
-
@Philipp Dahse,因为存储嵌入式文档会导致文档大小增加并重新定位到另一个磁盘空间,从而导致写入缓慢
-
拆分帖子和 cmets 会导致读取速度慢得多。仔细考虑哪种速度更重要。
标签: node.js mongodb express mongoose async.js