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

Ways to extend div to fill the rest of the page's vertical space

Apologies, my search has yielded many results, but none that directly address my specific issue. It appears that there is a proliferation of div-height problems on this platform. :-( Here is the layout I am working with for testing purposes: <!DOCTYPE ...

Sequelize synchronization does not generate the database table

I am currently working on a project with the following directory structure: ├── index.ts ├── package.json ├── package-lock.json ├── src │ ├── controllers │ ├── models │ │ └── repository.ts │ ├ ...

methods for transferring javascript variables to modal

<div> <h5> <a href="<?php echo base_url(); ?>/vendor/home/projects" >Return to Projects</a> </h5> <div> <div class="container"> <div class="row"> ...

Utilizing Chrome Context Script plugin to monitor page changes: A step-by-step guide

Currently, I am in the process of creating a basic Chrome extension with the purpose of removing specific DOM elements from a particular website. In my manifest.json file: { "name": "example", "version": "1.0", "description": "example description" ...

Cannot display GIF file from the SRC directory in a React application

I am trying to display a gif from the "/src/images" folder in my component, but I keep getting my "old" value displayed instead. What could be causing this issue? Snippet from Danke.js site: import Confetti from "../images/confetti.gif"; <Box sx={{ ju ...

Adjust an IntervalObservable's interval by incorporating a variable

I've encountered an issue with a component that needs to run code at regular intervals without pausing. I'm currently using an IntervalObservable and need to adjust the interval dynamically. While I can change the variable value using the setTime ...

What is the best way to incorporate one Div within another Div using JavaScript?

I have a single main div with an id, and I am looking to insert 4 additional child divs inside it. Each of these child divs will then contain 5 more divs each. The code snippet that I currently have is as follows: $( document ).ready(function() { for( ...

Is the Angular 16 button being properly interpreted?

I recently added a primeicon/primeng button in my Angular 16 project using the following code snippet: <button pButton label="Clear" class="p-button-outlined" icon="pi pi-filter-slash" (click)="clear(dt)">&l ...

Unleashing the potential of Chrome's desktop notifications

After spending the past hour, I finally found out why I am unable to make a call without a click event: window.webkitNotifications.requestPermission(); I am aware that it works with a click event, but is there any way to trigger a Chrome desktop notifica ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

Removing a document from an array within a MongoDB collection

I have a MongoDB schema that looks like this. { userID: 19202, products: [{ id: 020, name: 'first' }] } My goal is to remove items from the product array based on their id. I tried using the following command but it didn't give any ...

The aggregation must be a nonempty array with either $and, $or, or $nor operations

When applying filters, users have the option to skip all other filters and only apply the nearby filter. The issue arises when both tags and cuisines filters are skipped, resulting in an exception. Below is the code snippet: const query = []; if (cuisines) ...

Modifying pagination numbers with Reactjs: A step-by-step guide

I am currently working on Reactjs (nextjs) and I have successfully integrated the "Nextjs" framework. The pagination is working fine, but the buttons are displaying as "1,2,3,20" instead of "1,2...20" (showing all numbers without using "..."). How can I mo ...

Determining block time based on block number within Polygon Mumbai Testnet

Is there a dependable method to identify the production time of a specific block in Polygon Mumbai Testnet using only its block number? I am unable to utilize an Api for this purpose and am seeking a more user-friendly computational solution. Any suggest ...

Dynamic views loaded from ui-router can cause compatibility issues with running Javascript

Currently, I am facing an issue while attempting to load a template into a UI-View using UI-Router. Although the JavaScript is loaded, it does not run on the loaded views. The situation unfolds as follows: I have developed a template in HTML containing all ...

Interference with ElementClickInterceptedException in Selenium is caused by the presence of a WebPack iframe within an Angular application, despite implementing WebDriverWait

Everything was going smoothly with my automation code until suddenly, an ElementClickIntercepted exception started occurring when trying to click the "Sign In" button on the login screen: public class LoginPage { private readonly IWebDriver driver; ...

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

Tips for dodging drawn-out sequences of periods

When working with nested objects using dot notation, it can be tedious to constantly check if each previous object exists. I'm looking for a solution that avoids lengthy if chains like if (a && a.b && a.b.c && a.b.c[0] ... ) ...

Reveal each element individually upon clicking the button

I am trying to display 5 div elements one by one when clicking a button, but the current code is not working. I am open to alternative solutions for achieving this. Additionally, I want to change the display property from none to flex in my div element. ...

Navigate to the homepage section using a smooth jQuery animation

I am looking to implement a scrolling feature on the homepage section using jquery. The challenge is that I want the scrolling to work regardless of the page I am currently on. Here is the HTML code snippet: <ul> <li class="nav-item active"> ...