【问题标题】:How to effectively fetch comments for posts with MongoDB/mongoose?如何使用 MongoDB/mongoose 有效地获取帖子的评论?
【发布时间】: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


【解决方案1】:

尝试通过mongoose populate 和aggregate 来实现。示例代码如下。

var Post = mongoose.model('Post', PostSchema);
var Comment = mongoose.model('Comment', CommentSchema);

Comment.aggregate([
    {$group: {_id: '$_post', comments: {$push: '$body'}}}
    // ...
    ], function(err, result) {
        if (err)
           // error handling
        Post.populate(result, {path: "_id"}, function(err, ret) {
            if(err)
                console.log(err);
            else
                console.log(ret);
        });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2019-04-13
    • 2018-08-16
    • 1970-01-01
    • 2015-10-14
    相关资源
    最近更新 更多