Mongo:如何查询靠近特定位置的另一个集合中的文档?

时间:2019-06-07 01:41:43

标签: node.js mongodb mongoose

我有2个收藏集:

var shopSchema = new Schema({
    name: String,
    location: {type: [Number], index: '2dsphere'}, //lng, lat
})

var favoriteShopSchema = new Schema({
    shop: {type: Schema.Types.ObjectId, ref: 'Shop'},
    isActive: {type: Boolean, default: true},
    created: {type: Date, default: new Date()}
})

我需要在特定位置附近找到喜欢的商店。

如果要用于商店而不是最喜欢的商店,我只需这样做:

Shop.find({ 
    location:
            { $near:
                {
                    $geometry: {type: "Point", coordinates: [location[0], location[1]]}, //location: [lng,lat]
                    $maxDistance: 20 * 1000
                }
}

但是对于喜欢的商店怎么办?

为了使情况复杂化,我想限制结果并按页面进行管理。

总结我的尝试:

1。

let perPage = 10;
let page = req.body.page || 1;

let offers = await FavoriteShop.find({
            "shop.location":
                { $near:
                        {
                            $geometry: {type: "Point", coordinates: [req.body.lng, req.body.lat]}, //location: [lng,lat]
                            $maxDistance: 5 * 1000
                        }
                }
        })
            .populate('shop', 'name location')
            .skip((perPage * page) - perPage)
            .limit(perPage)
            .exec(async function(err, results) {
                if(err || !results) {
                    return res.status(404).end();
                }
                return res.send({
                    offers: results,
                    current: page,
                    pages: Math.ceil(results.length / perPage)
                })
            });

->我猜没有正常的结果,因为populate()是在find()之后获取的。

2。

offers = await FavoriteShop.aggregate([
    { "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": {type: "Point", coordinates: [req.body.lng, req.body.lat]}
            },
            "spherical": true,
            "limit": 150,
            "distanceField": "distance",
            "maxDistance": 10 * 1000
        }},
    { "$lookup": {
            "from": "shops",
            "localField": "shop",
            "foreignField": "location",
            "as": "offer"
        }}
]);

->“ MongoError:geoNear命令失败:{ok:0.0,errmsg:“ geoNear没有地理索引”}”

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我解决了这样的问题:

Shop.aggregate([
        {
            $geoNear: {
                near: {
                    type: "Point",
                    coordinates:  [req.body.lng, req.body.lat]
                },
                distanceField: "distance",
                includeLocs: "location",
                spherical: true,
                maxDistance: 1 * 1000
            }},
        { $lookup: {
                from: "favoriteshops",
                localField: "_id",
                foreignField: "shop",
                as: "offers"
            }
        },
        { $unwind: '$offers' }
    ]);