Mongoose issues with geo spatial queries

February 06, 2018, at 1:34 PM

I came across this issue when trying to perform a geospatial query in Mongoose (5.x). I tried using the approach from the following website: link. Note there is a mistake here according to GeoJSON spec longitude needs to go before latitude.

I have the following dog schema:

let mongoose = require("mongoose");
let dogSchema = new mongoose.Schema({
    name: String,
    age: Number,
    breed: String,
    personality: String,
    isTherapyDog: Boolean,
    behaviourWithStrangers: String,
    description: String,
    geo: {
        type: [Number],
        index: '2d',
    owner: {
        type: mongoose.Schema.ObjectId,
        ref: "User",
    created: {
        type: Date,
    url: String,
module.exports = mongoose.model("Dog", dogSchema);

Instead setting the key in the schema, I also tried the following:

dogSchema.index({ geo: '2d' });

I also tried using '2dsphere' instead. I also tried setting the index to 2d using the mongo shell and ensuring it is 2d.

I have the following code in app.js file where I attempt to perform a geospatial query. (Yes the query should not be in the app.js file and should be in a different route, but this is for testing purposes only)

var distance = 1;
var query = Dog.find({
    geo: {
        $near: [
query.exec(function(error, dogs) {
    if (error) {
    } else {

When I run this file I get one of the following results.

  1. The array printed out by dogs is empty, despite there being a number of dogs in the vicinity

  2. I get an error with $geonear query that index of geo is not found.

How do I fix this and perform query correctly? I have tried other tutorials from other sources and they all result in the same error. I prefer solution in MONGOOSE over the native MONGO client.

Flowtypes, how to reduce duplication in Model-like class definitions

Flowtypes, how to reduce duplication in Model-like class definitions

We're currently adopting flow, and I'm running into an interesting problemIn one of our code-bases, we use a pattern roughly as follows

Referencing Schemas in Mongoose

Referencing Schemas in Mongoose

I have a couple models that are in going to be held in separate files and I can't seem to find a way to reference them without resorting to having them in the same file

Access socket emitter with in other modules nodejs express

Access socket emitter with in other modules nodejs express

I'll preface this by saying I am new to nodejs in generalComing from the world of C#, it's a completely different way of thinking for me

Node - Run code after return statement

Node - Run code after return statement

Is there any way to run a block of code after the return of a function in node js?