Я пытаюсь сгруппировать сообщения, полученные пользователем, по имени отправителя. Я хочу отображать последнее сообщение в каждом чате, как в WhatsApp.
Я пробовал использовать match и group. Я нашел решение, рекомендующее использовать joins($lookup), но в конце концов понял, что может быть достаточно использования match и group.
userId я получаю от маршрута
Message.aggregate(
[
{ $match: { $or: [{ 'from.userId': userId }, { 'to.userId': userId }] } },
// { $project: {...FIELDS}}, ///what to use here
{ $sort: { timestamp: -1 } },
{
$group: {
"_id": {
'fromuserId': userId,//confusion here
// 'toUserId': userId,
// 'to.user'
},
// 'userId': { $first: '$from' },
// 'userId': { $first: '$to' },
msg: { $first: '$msg' },
timestamp: { $first: '$timestamp' }
}
}
]
).exec((err, results) => {
if (err) {
console.info('err===>', err);
}
console.info('results|||', results)
})
моя схема такова:
const MessageSchema = new mongoose.Schema({
to: {
userId: {
type: mongoose.Schema.Types.ObjectId,// to be sent from client side
ref: "User",
required: true
},
name: {
type: String,
},
pictureUrl: {
type: String,
}
},
from: {
userId: {
type: mongoose.Schema.Types.ObjectId,// to be sent from server side
ref: "User",
required: true
},
name: {
type: String,
},
pictureUrl: {
type: String,
}
},
message: {
type: String,
required: true
}
},
{
timestamps: true
}
);
Я получаю пустой массив в качестве вывода. Мне нужно знать, как использовать id в $group. также как использовать to.userId или from.userId в id. это не позволяет точку (.) внутри id.
все еще получаю пустой массив
может быть для отладки, давайте сохраним _id:userId и проверим, приходят ли какие-либо данные.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


эй, внутри
$group, вместо_idвы пытались передать"_id": { 'fromuserId': "$from.userId", 'toUserId': '$to.user', }