如何在mongodb中获取数组的另一个参与者的详细信息



我想获取聊天的另一个参与者(只有两个参与者(的详细信息,但我只能获取获取数据的人的详细信息。

下面是我的代码

//Get ChatList
export const getChats = async(req, res) => {
const userId = req.params.id
try {
const chats = await ChatModel.aggregate([
{
$match: {
participantId : userId
}
},
{ $addFields: {"userObjectid": {"$toObjectId": userId}}},
{
$lookup: {
from : "users",
localField: "userObjectid",
foreignField: "_id",
as : "userDetails"
}
},
{
$project: {
"_id": 1,
"participantId": 1,
"lastMessage": 1,
"unread": 1,
"updatedAt": 1,
"userDetails._id" : 1,
"userDetails.username" : 1,
"userDetails.firstname" : 1,
"userDetails.lastname" : 1,
"userDetails.profilePicture": 1
}
}
])

res.status(200).json(chats.sort((a,b) =>{
return a.updatedAt - b.updatedAt;
}))
} catch (error) {
res.status(500).json(error)
}
}

我已经解决了这个问题,我使用了聚合开关案例来实现这个解决方案。

//Get ChatList
export const getChats = async (req, res) => {
const userId = req.params.id;
try {
const chats = await ChatModel.aggregate([
{
$match: {
participantId: userId,
},
},
{
$addFields: {
sender: { $indexOfArray: ["$participantId", userId] }
}
},
{
$addFields: {
recipient: {
$switch: {
branches: [
{ case: { $eq: ["$sender", 0] }, then: 1 },
{ case: { $eq: ["$sender", 1] }, then: 0 },
],
default: 0,
}
}
}
},
{
$addFields: {
userObjectid: {
$toObjectId: { $arrayElemAt: ["$participantId", "$recipient"] },
},
}
},
{
$lookup: {
from: "users",
localField: "userObjectid",
foreignField: "_id",
as: "userDetails",
},
},
{
$project: {
_id: 1,
participantId: 1,
lastMessage: 1,
unread: 1,
updatedAt: 1,
"userDetails._id": 1,
"userDetails.username": 1,
"userDetails.firstname": 1,
"userDetails.lastname": 1,
"userDetails.profilePicture": 1,
},
},
]);
res.status(200).json(
chats.sort((a, b) => {
return a.updatedAt - b.updatedAt;
})
);
} catch (error) {
res.status(500).json(error);
}
};

相关内容

最新更新