mongoosejs 如何 关联字段?

RT,例如下面这种业务场景:

const docs = await SendMessage.aggregate([
    {
        $match: {
            channel_id: Types.ObjectId(id),
        }
    },
    {
        $project: {
            text: '$msg_content',
            createdAt: '$send_time',
            user: {
                _id: '$msg_from', // 某个userId
                name: null, // 如何根据userId在这里给它相关username
            },
        }
    },
    {
        $sort: {
            _id: -1,
        }
    },
])
阅读 1.5k
1 个回答

我在用mongoose,后来发现aggregate下面$lookup这个方法可以解决问题!

const docs = await SendMessage.aggregate([
    {
        $match: {
            channel_id: Types.ObjectId(id),
        }
    },
    {
        $lookup: {
            from: 'users',
            localField: 'msg_from',
            foreignField: '_id',
            as: 'users',
        }
    },
    {
        $project: {
            text: '$msg_content',
            createdAt: '$send_time',
            user: {
                _id: '$msg_from',
                name: {
                    $arrayElemAt: ['$users.username', 0],
                },
                avatar: {
                    $let: {
                        vars: {
                            username: {
                                $arrayElemAt: ['$users.username', 0],
                            },
                        },
                        in: {
                            $concat: ['https://dummyimage.com/200x200/00E67D/000.jpg&text=', '$$username'],
                        },
                    },
                },
            },
        }
    },
    {
        $sort: {
            _id: -1,
        }
    },
])
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题