我使用 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);
但是,不幸的是,我的模型没有 group
方法。你有什么解决方案,让这个工作?
谢谢。
最佳答案
使用 $lookup 填充的示例,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;
}
)
关于javascript - Mongoose - 如何分组和填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25231022/