【问题标题】:Nested query with mongoose使用猫鼬的嵌套查询
【发布时间】:2015-11-11 16:39:25
【问题描述】:

我有三个模型:用户、帖子和评论

var User = new Schema({
    name: String,
    email: String,
    password: String // obviously encrypted
});

var Post = new Schema({
    title: String,
    author: { type: Schema.ObjectId, ref: 'User' }
});

var Comment = new Schema({
    text: String,
    post: { type: Schema.ObjectId, ref: 'Post' },
    author: { type: Schema.ObjectId, ref: 'User' }
});

我需要获取用户评论过的所有帖子

我知道这应该是一个非常简单和常见的用例,但现在我想不出一种方法来在没有多次调用和手动迭代结果的情况下进行查询。

我一直在考虑将comments 字段添加到Post 架构(我希望避免使用)并制作如下内容:

Post.find()
    .populate({ path: 'comments', match: { author: user } })
    .exec(function (err, posts) {
        console.log(posts);
    });

在不修改我的原始架构的情况下有任何线索吗?

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你基本上有几种方法可以解决这个问题。

    1) 不填充。这使用了多次调用的承诺。首先查询特定用户的Comment 模型,然后在返回的回调中使用 cmets 中的帖子 ID 来获取帖子。您可以像这样使用 promises

    var promise = Comment.find({ "author": userId }).select("post").exec();
    promise.then(function (comments) {
        var postIds = comments.map(function (c) {
            return c.post;
        });
        return Post.find({ "_id": { "$in": postIds }).exec();
    }).then(function (posts) {
        // do something with the posts here
        console.log(posts);
    
    }).then(null, function (err) {
        // handle error here
    });
    

    2) 使用填充。使用给定的 userId 查询特定用户的 Comment 模型,只选择您想要的帖子字段并填充它:

    var query = Comment.find({ "author": userId });
    query.select("post").populate("post");
    query.exec(function(err, results){    
        console.log(results);
        var posts = results.map(function (r) { return r.post; });
        console.log(posts);
    }); 
    

    【讨论】:

    • 看起来很有希望(没有双关语),但当我说我正在寻找避免多次调用的方法时,这正是我在帖子中所指的(有两个 finds)和迭代(地图)。
    • @javorosas 用另一种方法更新了我的答案,该方法不需要多次调用,但会操纵结果数组以仅返回帖子,更接近您正在寻找的内容。
    猜你喜欢
    • 2021-03-23
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 2015-04-10
    • 2019-04-06
    • 1970-01-01
    相关资源
    最近更新 更多