我使用 MongoDB 和 Mongoose 作为我的 ODM,我尝试使用以下命令进行查询populate
and 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 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;
}
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)