Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geoNear exception: 'near' field must be point

I have run the following query successfully in the mongo shell:

db.runCommand({
    geoNear : "stores",
    near : { type : "Point", coordinates : [ -3.978, 50.777 ] },
    spherical : true,
    limit : 10
})

I am trying to convert this into a mongoose query for my node service as shown in the docs.

Store.geoNear(
    { type : "Point", coordinates : [-3.978, 50.777]}, 
    { spherical : true, limit : 10 }, 
    function (error, results, stats) {
    //do stuff with results here
});

This is returning the following error:

MongoError: exception: 'near' field must be point

My Store schema is defined like this:

var storeSchema = new Schema({
    // irrelevant fields...
    locations : [
        {
            address : {
                streetAddress : String,
                postalCode : String
            }
            coords : {
                type : [Number],
                index : '2dsphere'
            }
        }
    ]
})

There is only one 2dsphere index on the collection, and as I mentioned, it works through the shell, just not with mongoose.

Edit: Other things I've tried without success:

Falling back to using mongodb native driver (same error, so I suspect it's mongodb rather than mongoose causing the problem):

Store.collection.geoNear(
    { type : "Point", coordinates : [-3.978, 50.777]}, 
    { spherical : true, limit : 10 }, 
    function (error, results, stats) {
    //do stuff with results here
});

Falling back to using legacy coordinates instead of geopoints (both mongoose and native (same error)):

Store.geoNear(
    -3.978, 50.777, 
    { spherical : true, limit : 10 }, 
    function (error, results, stats) {
    //do stuff with results here
});

Using runCommand from mongoose (this errors differently, saying that Store.db.command is not a function - the correct way to call this from mongoose would be an acceptable answer):

Store.db.command({
    geoNear : "stores",
    near : { type : "Point", coordinates : [ -3.978, 50.777 ] },
    spherical : true,
    limit : 10
}, function(error, results){})
like image 325
Carasel Avatar asked Nov 08 '22 15:11

Carasel


1 Answers

Finally managed to work out how to fall back to use runCommand via the mongodb native driver:

Store.db.db.command({
    geoNear : "stores",
    near : { type : "Point", coordinates : [ -3.978, 50.777 ] },
    spherical : true,
    limit : 10
}, function(error, results){})
like image 69
Carasel Avatar answered Nov 15 '22 06:11

Carasel