No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location.

location: {
      type: {
      type: String,
      enum: ['Point'],
      required: true
    },
    coordinates: {
      type: [Number],
      required: true
    },
    index: '2dsphere'
   },

The controller function for creating a tour is as follows:

const createTour = async (req, res) => {
   var newTour = new TourDB.Tour({
      ...
      location: { type: 'Point', coordinates: [req.body.tour.loc[0], req.body.tour.loc[1]] },
      ...
   })

   newTour.save(async (err, doc) => {
      if (!err) {
         return res.status(200).send(doc)
      } else {
         return res.status(500).send({ errorMessage: err })
      }
   })

In the frontend, a new Tour can be created with this property: loc: [this.lng, this.lat],

This is how it will look in MongoDB:

https://i.stack.imgur.com/m0qqD.png

To query the location within a radius, I attempted the following in my controller (radius and maxDistance values are hardcoded for testing):

const getTourByRadius = async (req, res) =>  {
   let coords = [];
   coords[0] = 9.825031;
   coords[1] = 48.625107799999995

   const maxDistance = 10;

   try {
      const tour = await TourDB.Tour.find({
         location: {
            $near: {
               $geometry: {
                  type: "Point",
                  coordinates: coords
               },
               $maxDistance: maxDistance
            }
         }
      }).exec()
      res.send(tour)
   } catch (err) {
      res.send(err)
   }
}

However, I am currently receiving an empty [] array as a result. What could I be doing wrong?

Answer №1

What is the distance you are looking for? Here is a sample code snippet:

db.tour.insertOne({
   location: { type: 'Point', coordinates: [9.8238464, 47.627712] },
   cityName: "Geislingen"
})

db.tour.createIndex({ location: "2dsphere" })

let coords = [];
coords[0] = 9.825031;
coords[1] = 48.625107799999995

db.tour.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: coords },
        distanceField: "distance",
        spherical: true
     }
   }
])

The output would be:

{ 
    "_id" : ObjectId("608a73d51ef0d7c449c3e4c6"), 
    "location" : {
        "type" : "Point", 
        "coordinates" : [
            9.8238464, 
            48.627712
        ]
    }, 
    "cityName" : "Geislingen", 
    "distance" : 302.71595482740787
}

If you set maxDistance to more than 302.7 meters, it will return the following document:

let maxDistance = 303
db.tour.find(
   {
      location: {
         $near: {
            $geometry: { type: "Point", coordinates: coords },
            $maxDistance: 303
         }
      }
   }
)

{ 
    "_id" : ObjectId("608a73d51ef0d7c449c3e4c6"), 
    "location" : {
        "type" : "Point", 
        "coordinates" : [
            9.8238464, 
            48.627712
        ]
    }, 
    "cityName" : "Geislingen"
}

Remember to specify the distance in meters for GeoJSON points and in radians for legacy coordinate pairs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Data string not being converted correctly to date format

Here is a table I am currently working with: ID DateColumn 1 3/7/2019 5:29:38 AM 2 3/8/2019 5:28:38 AM 3 3/7/2019 5:30:38 AM 4 3/7/2019 5:31:38 AM The date column in this table is being processed as a string when bound to the grid. To ...

AngularJS - Ensuring the <script> tag is included only after all directives have been rendered

Forgive me if this question has been asked before. I've spent quite some time looking for a solution to no avail. I'm in the process of converting an existing application, which relies heavily on jQuery, to utilize AngularJS. However, I've ...

Javascript chart

Hello everyone, I am diving into the world of fetch API. Currently, I am faced with a challenge where I need to generate the following list items: <li>Zimmerman, Paul</li> <li>Yimmerman, Raul</li> <li>Limmerman, Caul</li> ...

What advantages does incorporating a prefix or suffix to a key provide in React development?

Is there any advantage to adding a prefix or suffix to the key when using an index as a key in React (in cases where no other value such as an id is present)? Here's an example: const CustomComponent = () => { const uniqueId = generateUniqueId( ...

Steps to develop a runnable Express API

After developing a basic yet fully functional Node.js Express API application using JavaScript, I am now looking to convert it into an executable file that can be run on Windows systems. The main reason behind this is to provide clients with the option of ...

How can the values from the scale [-60, -30, -10, 0, 3, 6, 10] be converted to a decimal range of 0-1 through

Thank you for helping me with so many of my issues. <3 I'm certain that someone has already solved this, but I'm unsure of the specific mathematical term (I've attempted reverse interpolation and others, but with no luck) so I am present ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...

What is preventing me from being able to update this specific MongodDB document within the initial callback function, even though I am successfully able to update other documents without any problems?

Apologies for any confusion caused by the title, as I struggled to condense the issue into a single question. Currently, I am in the process of implementing a commenting system for a generic article posting and reading web application using the MEAN stack. ...

Is it possible to combine EJS compilation and html-loader in the html-webpack-plugin?

I need the html-webpack-plugin to generate my html using my .ejs template that contains <img> tags. The html-loader can update the image URLs in my <img> tags created by Webpack, so I am including it in my configuration: test: /& ...

Error encountered while parsing Node.js code for MySQL query execution

I am encountering an error message from Node that reads: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TIMESTAMPDIFF(second, entered_at, c ...

The FlatList glides effortlessly in any direction

My FlatList allows me to drag and move it in all directions (up/down/right/left) even though it appears vertically due to styling. The scroll bar still shows horizontally, which I want to disable. How can I achieve this? This is the code snippet for using ...

Merging two arrays by their corresponding IDs and indexes

Within my current project, I am working with two arrays. The first array, arr1, contains a questionID property that I need to use to combine it with arr2 based on the condition where arr1 questionID equals arr2 index. For example, if arr1 questionID is 1, ...

Tips for making an ajax call in Angular 6

As a backend developer, I have limited experience with Angular. How can I send an ajax request from Angular to test my API? The request needs to be sent before clearing the localeStorage. Can you provide guidance on how to achieve this? <button (clic ...

Ways to iterate through a JSON formatted array variable using JavaScript

Below is my code snippet, used to plot all the locations fetched from my database onto a Google map. $.ajax({ url:"http://localhost/church_finder/index.php/MapController/search_church", type:'POST', data: ...

Having trouble downloading a PDF file on a local server with React and the anchor tag element

Having trouble downloading a pdf file from my react app to my Desktop. I've reached out for help with the details How to download pdf file with React. Received an answer, but still struggling to implement it. If anyone new could provide insight, that ...

Electron's start script leads to project failure

Despite extensively searching the internet for a solution, I have yet to find a definitive answer that actually works. My last resort was downloading the example from Electron's website and directly inserting the scripts into my project. However, whe ...

"Encountering an issue with Multer where req.file is displaying as undefined in NodeJS

Recently, I followed the advice of several YouTubers and used multer for file upload in my project. However, despite correctly defining all the functions, req.file always appears as undefined. booking_route.js const express = require('express'); ...

What is the best way to utilize imported classes, functions, and variables within an Angular 2 template?

I've come up with a solution for incorporating static content into a template, but I'm unsure if it's the best approach. I would like to know if there is an official or more efficient method of achieving this. Here's an example showcas ...

Order by the numerical value within a string field in a MongoDB collection

I have a collection of data stored in my MongoDB database like this. { "_id": ObjectId "username": "username-7" }, { "_id": ObjectId "username": "username-1" }, { "_id": Object ...

Encountered an issue with md-autocomplete: Attempting to read property 'success' of an undefined element

I encountered an issue while using Material Angular framework and md-autocomplete. The error message I receive is: Cannot read property 'success' of undefined. Below is the snippet of my code: /*My app.js*/ var app = angular.module('app&apo ...