Efficiently sift through a vast assortment using a filtering method

Currently, I am developing an application similar to Uber which involves managing a collection of drivers with their current positions (latitude and longitude).

One specific requirement is to find drivers who are within a 200-meter distance from the user's current position. To achieve this, I implemented the following method in the driver schema:

driverSchema.methods.CloseDriver = function (userCurrentPosition,next) {
  try {    
    const distance = geolib.getPreciseDistance(
      userCurrentPosition,
      this.currentPosition
   );
   return distance <= 200
  } catch (error) {
      return next();
  }
}

After defining this method, I handle a POST request containing the user's currentPosition as follows:

     const parsedBody = Object.setPrototypeOf(req.body, {});

      if(parsedBody.hasOwnProperty("latitude") && parsedBody.hasOwnProperty("longitude")){
        const { latitude , longitude } = req.body
        const currentPosition = { latitude , longitude }
        const drivers = await Driver.find({})
        const eligibleDrivers =  drivers.filter((driver)=> driver.CloseDriver(currentPosition))
        return res.status(200).json({
          status : 200 , 
          eligibleDrivers
        });

In case we have a large array of drivers, is there a more efficient way to accomplish this task?

Answer №1

To efficiently filter drivers based on their location, you can utilize the $geoNear method in conjunction with aggregate. This allows you to incorporate the location filtering directly into your query without having to load all the drivers and then apply the filter in JavaScript.

Here's an example of how you can implement this:

db.drivers.aggregate([
   {
     $geoNear: {
        near: { type: "Point", coordinates: [ CurrentLongitude, CurrentLatitude ] },
        distanceField: "distance",
        maxDistance: 2,
        includeLocs: "currentPosition",
        spherical: true
     }
   }
]);

In order for this to work, ensure that the currentPosition latitude and longitude coordinates are stored in your schema in the following format:

"currentPosition": {
      "type" : "Point",
      "coordinates" : [ -73.9375, 40.8303 ]
   },

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

The file could not be loaded as a result of Multipart: The boundary was not detected

Having trouble uploading images from my desktop due to a multipart boundary error. How can I set a proper boundary for image uploading? Any advice would be greatly appreciated as this is my first time attempting image uploads. Implementing an HTML event l ...

Retrieve a compiled array of parameters for ExpressJS

I am attempting to gather all the parameters from a path in a GET request. app.get('/*',function(req, res) { console.log(req.params[0]); res.send('testing'); }); Nevertheless, when I visit the URL localhost/test/test1, the par ...

Retrieve the designated element from an array of JSON data in SPLUNK

As a newcomer to the world of Splunk, I am facing a challenge with handling JSON data. Here is an example of the JSON data I am working with: "request": { "headers": [ { "name": "x-real-ip", "value": "10.31.68.186" ...

How to highlight all the text within a 'pre code block' when double-clicked using JavaScript

Is there a way to make code blocks on my blog automatically selected when double-clicked without using jQuery? Here is the code I have so far: I apologize if this is a silly question, I am still learning! <script type="text/javascript" src="https://c ...

Click to remove the accordion div

My query is regarding an accordion feature that I have implemented. <div id="accordion" class="accord"> <h2> <a href="#">Item1</a></h2> <div> Content1 </div> <h2 > &l ...

Efficiently manage large datasets with Vue.js using the expand/collapse list AJAX pattern

Within my vuejs application, there is a page where I aim to showcase a list of clients. When a user expands an individual client row, it should reveal a list of proposals specific to that client. Additionally, there is an expand/collapse functionality for ...

The server's socket.io listener unexpectedly triggers twice without any clear explanation

Currently, I am in the process of developing an application that includes a chat feature utilizing express.js, react.js, and socket.io. If you would like to view a minimal version with the bug replicated, please visit this Github link. The issue at hand i ...

The Seamless Integration of RESTful APIs and User Sessions

If a RESTful API is stateless, what is the best way to manage user sessions in this scenario? For example, if I have an API that enables users to borrow books without requiring them to log in to browse the collection, how should I handle this situation? ...

The imgAreaSelect plugin is up and running successfully. Now, I am looking to utilize the x and y coordinates to make updates to the image stored in the database. How can I

After retrieving the dimensions and coordinates from the jQuery plugin imgAreaSelect, I am looking for guidance on how to update the image in my database based on this selection. The database contains a tempImage and Image field, and my goal is to allow ...

Error message when using Vue Global Filter: Value undefined is not defined

Trying to format currency, I initially attempted to use a global filter in Vue: Vue.filter('formatMoney', (val) => { if (!value) return '' val = val.toString() return val.replace(/\B(?=(\d{3})+(?!\d))/g, ",") ...

Node and Express are correctly logging the response, however the React frontend is logging an entirely different message

Currently, I am in the process of developing a form for an eCommerce platform that allows the administrator/owner to upload images to Cloudinary. At the moment, the image is being successfully uploaded to Cloudinary. Upon logging the response (using conso ...

Opening multiple dialogs in Jquery Dialog box

I have several images displayed on a single page. When each image is clicked, I want a dialog box to open. I currently have 6 instances of this setup in my HTML. However, when I click on an image, all 6 dialogs pop up with the same information as the first ...

Icon displayed within the input field

Is there a simple method to add an input text element with a clear icon on the right side, similar to the layout of the Google search box? I've searched, but I could only find instructions for placing an icon as the background of the input element. I ...

Discover the ins and outs of utilizing the Google+ Hangout API specifically for chatting purposes

I am currently working on a webpage and I want to include a hangout button that will allow users to connect with me and start chatting automatically when clicked. Here is the code I have so far: <script src="https://apis.google.com/js/platform.js" asy ...

Tips for positioning a modal in the center specifically for zoomed-in mobile devices

I created a modal that uses the following function to center itself: center: function() { var top=Math.max($window.height() - $modal.outerHeight(),0) / 2; var left=Math.max($window.width() - $modal.outerWidth(),0) / 2; $modal.css({ ...

Trigger Bootstrap Modal using ASP Razor code within MVC Model value execution

I have a web application built with ASP .NET Core and MVC. The app features a side menu that allows the user to navigate through different pages based on their workflow. For example, when a user logs in for the first time, they are directed to the Home pag ...

What are the steps to create a Node.js application and publish it on a local LAN without using Nodemon?

When working on a Node.js application, I often use the following commands to build and serve it locally: //package.json "build": "react-scripts build", To serve it on my local LAN, I typically use: serve -s build However, I have been wondering how I ...

Using Node.js to set a whitelist limit for express.json

In my Node.js backend, I have multiple routes that do not involve file uploads for regular users (with a limit of 50kb). However, I need to create specific routes for administrators to be able to upload files, which would require a higher express.json and ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Revamping repetitive JavaScript code for the pagination of Instagram Stories

I'm currently developing a website that utilizes fullpage.js and includes a section with multiple slides. These slides automatically transition every 10 seconds. I wanted to implement progress bars similar to those on Instagram, where each bar fills ...