0

我正在重构一些旧代码以希望加快速度并使信息更安全。为了做到这一点,我尝试使用 MongoDB 聚合框架让所有用户靠近特定位置。最初,这是通过在前端处理一些球面计算来解决的,但这样做会将lat, lng每个用户的坐标发送回前端,这是不安全的,并且会不必要地暴露用户的位置数据。

我的解决方案是使用聚合框架并$geoNear获取附近用户的列表,然后还填充一个以英里为单位的距离字段distanceAway。在我尝试设置分页之前,一切都运行良好。该$count阶段大大减慢了路线的执行。

下面是我的代码:

module.exports = async function findUsersNearLocationAggregate(baseLocation, page = 1, limit = 20) {
    // quick validation on location object passed
    if(!lodash.get(baseLocation, 'geometry.location', undefined)) 
        throw new Error('NO_LOCATION_SPECIFIED')

    //  Grab user location to use as location origin
    const { lat, lng } = baseLocation.geometry.location

    let query = {
        $geoNear: {
            near: { type: "Point", coordinates: [lng, lat] },
            distanceField: "distanceAway",
            spherical: true,
            distanceMultiplier: CONVERT_METERS_TO_MILES
        }
    }

    const users = await User.aggregate([
        query,
        { $skip: ((page - 1) * limit) },
        { $limit: limit }
    ])

    // const [{ count }] = await User.aggregate([
        // query,
        // { $count: 'count' }
    // ])

    return {
        user: users,                    
        // totalPages: Math.ceil(count / limit)
        // currentPage: page
    }
}

此函数旨在返回用户列表(limit一次 20 个)并显示其他数据,例如跟踪前端的分页并发出后续请求totalPagescurrentPage

当我注释掉以下行时:

    const [{ count }] = await User.aggregate([
        query,
        { $count: 'count' }
    ])

使用调用的路由的执行时间最长为 100 毫秒。当我在通话中评论它时,它会跳到大约 1100 毫秒。

有没有办法在不显着增加请求时间的情况下获得我正在寻找的分页数据?10X 似乎相当大。

4

0 回答 0