本文介绍了Mongoose - 如何分组和填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 MongoDB 和 Mongoose 作为我的 ODM,并且我尝试在同一语句中使用 populategroup by 进行查询.

I use MongoDB and Mongoose as my ODM and I'm trying to make a query using populate and group by in the same statement.

这是我的简单文档模型:

Here is my simple documents models :

var userSchema = new Schema({
    username: String
});

var messageSchema = new Schema({
    from: { type: Schema.ObjectId, ref: 'User' },
    to: { type: Schema.ObjectId, ref: 'User' },
    message: String,
    date: { type: Date, default: Date.now }
});

我只是想为一个用户获取每条消息,按他与之交谈的每个用户分组.我试过这样:

I'm just trying to get every messages for one user, group by each users he talks with. I tried like this :

this.find({ 'to': user })
    .sort({ 'date': 1 })
    .group('from')
    .populate(['from', 'to'])
    .exec(callback);

但是,不幸的是,我的模型没有 group 方法.你有什么解决方案可以让它工作吗?

But, unfortunately, my model doesn't have group method. Do you have any solution, to get this working ?

谢谢.

推荐答案

使用 $lookup populate 的示例,lookup 作为数组填充,因此 $unwind.

Example using $lookup populate, lookup populates as an array, hence the $unwind.

Message.aggregate(
    [
        { "$match": { "to": user } },
        { "$sort": { "date": 1 } },
        { "$group": { 
            "_id": "from",
            "to": { "$first": "$to" },
            "message": { "$first": "$message" },
            "date": { "$first": "$date" },
            "origId": { "$first": "$_id" }
        }},
        { "$lookup": {
             "from": "users",
             "localField": "from",
             "foreignField": "_id",
             "as": "from"
        }},
        { "$lookup": {
             "from": "users",
             "localField": "to",
             "foreignField": "_id",
             "as": "to"
        }},
        { "$unwind": { "path" : "$from" } },
        { "$unwind": { "path" : "$to" } }
    ],
    function(err,results) {
        if (err) throw err;
        return results;
    }
)

这篇关于Mongoose - 如何分组和填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:19