猫鼬找不到$ geoNear查询错误的索引

时间:2020-08-23 21:30:06

标签: node.js mongodb mongoose

我有以下代码尝试用猫鼬创建二级索引。我已经按照猫鼬官方文档实施了该文档(mongoose documentation:索引部分)。但是,当我通过邮递员发送GET请求时,出现错误“无法为$ geoNear查询找到索引”。我的理解是,就我而言,location等效于$geoNear对象,因此我的代码应该没问题(我知道这不好,这就是为什么我出错了)。任何意见或建议,将不胜感激。

app.js(获取端点)

app.get('/api/stores', (req, res) => {
    const zipCode = req.query.zip_code;

    const googleMapsURL = "https://maps.googleapis.com/maps/api/geocode/json";
    axios.get(googleMapsURL, {
        params: {
            address: zipCode,
            key : "KEY"
        }
        
    }).then((response) => {
        const data = response.data
        const coordinates = [
            data.results[0].geometry.location.lng,
            data.results[0].geometry.location.lat,
        ]
        
        Store.find({
            location: {
                $near: {
                    $maxDistance: 3218,
                    $geometry: {
                        type: "Point",
                        coordinates: coordinates
                    }
                }
            }
        }, (err, stores)=> {
            if (err) {
                console.log(err);
                res.status(500).send(err);
            } else {
                
                res.status(200).send(stores);
            }
        })
    }).catch((error)=> {
        console.log(error);
    })
})

store.js

const mongoose = require('mongoose');

const storeSchema = mongoose.Schema({
    storeName: String,
    phoneNumber: String,
    address: {},
    openStatusText: String,
    addressLines: Array,
    location: {
        type: {
            type: String,
            enum: ['Point'],
            required: true
        },
        coordinates: {
            type: [Number],
            required: true
        }
    }
})


storeSchema.index({ location : "2dsphere"}, {sparse: true});
module.exports = mongoose.model('Store', storeSchema);

enter image description here

2 个答案:

答案 0 :(得分:0)

在MongoDB中创建新索引时,可能必须删除表以使索引正确应用。尝试在新表上创建索引。这样行吗?

答案 1 :(得分:0)

我通过首先创建一个新的数据库和集合(我正在使用名为<dbname>的默认数据库)解决了这个错误。当我发送要存储在MongoDB中的数据的POST请求时,出现MongoError:无法提取地理键。我通过遵循该线程(reference)修复了此错误。完成这些步骤后,我的GET请求开始工作,并且索引已成功创建。

相关问题