猫鼬在一个字段中处理两个ref ObjectID以获取ObjectId的每个集合

时间:2020-09-13 09:17:07

标签: node.js mongodb express mongoose aggregation-framework

我在猫鼬和rest API方面还很新,我在检索每个集合时都遇到了问题,请参考另一个文档

所有这些模式都经过编辑以使其易于阅读,因为在实际情况下,我有更多字段认为不需要显示

我有一个user schema数据,如下所示:

{
    "_id": "123"
    "username": "Paijo",
    "email": "paijo@gmail.com"
}
{
    "_id": "345"
    "username": "Flix",
    "email": "Flix@gmail.com"
}

我有message schema这样的数据:

{
    "_id": "5f525b2ac1267e868e882fbc",
    "roomId": "123_345",
    "latestMessage": "Bisa lahh cujkkkk",
    "updatedAt": {
        "$date": "2020-09-05T07:00:27.846Z"
    },
    "createdAt": {
        "$date": "2020-09-04T15:20:10.840Z"
    }
}

我想查询user _id中是否有roomId,并检索user schemamessage schema的所有字段。

因此,假设我使用user _id 123登录,我想获取roomId中包含123的消息以及345的详细用户,

我想要获取的预期结果是:

{
    "_id": "5f525b2ac1267e868e882fbc",
    "roomId": "123_345",
    "latestMessage": "Bisa lahh cujkkkk",
    "updatedAt": {
        "$date": "2020-09-05T07:00:27.846Z"
    },
    "createdAt": {
        "$date": "2020-09-04T15:20:10.840Z"
    },
    "username": "Flix", // get result from user schema which has _id 345
    "email": "Flix@gmail.com" // get result from user schema which has _id 345
}

目前,我只能通过此查询来获取包含_id个用户登录名的所有消息,但我不知道如何在roomId中获取另一个ID的详细用户

exports.listChat = async (req, res)=>{
  const userID = req.userID
  const listChat = await ChatRoom.find({roomId: new RegExp(userID)}).select("-message")
  console.log('listChat' , listChat)

  res.send(listChat)
}

1 个答案:

答案 0 :(得分:1)

您可以首先使用$split并定义两个单独的子字段:me(当前用户)和other-您想用于$lookup的值。

db.message.aggregate([
    {
        $addFields: {
            members: {
                $let: {
                    vars: { mem: { $split: [ "$roomId", "_" ] } },
                    in: {
                        me: { $arrayElemAt: [ { $filter: { input: "$$mem", cond: { $eq: [ "$$this", "123" ] } } }, 0 ] },
                        other: { $arrayElemAt: [ { $filter: { input: "$$mem", cond: { $ne: [ "$$this", "123" ] } } }, 0 ] },
                    }
                }
            }
        }
    },
    {
        $match: {
            "members.me": "123"
        }
    },
    {
        $lookup: {
            from: "user",
            localField: "members.other",
            foreignField: "_id",
            as: "user"
        }
    },
    {
        $unwind: "$user"
    },
    {
        $project: {
            _id: 1,
            roomId: 1,
            latestMessage: 1,
            updatedAt: 1,
            createdAt: 1,
            username: "$user.username",
            email: "$user.email",
        }
    }
])

Mongo Playground