我使用MongoDB和Mongoose作为我的ODM,我正在尝试使用populate和group by在同一语句中进行查询.
这是我的简单文档模型:
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 }
});
我只是试图为每个用户收集每条消息,由他与之交谈的每个用户进行分组.我试过这样的:
this.find({ 'to': user })
.sort({ 'date': 1 })
.group('from')
.populate(['from', 'to'])
.exec(callback);
但是,不幸的是,我的模型没有组方法.你有任何解决方案,让这个工作吗?
谢谢.
解决方法:
使用$lookup populate的示例,lookup填充为数组,因此$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;
}
)