Exploring MongoDB Location Searching in Node.js with Radius Functionality | #CodeWithNaf

Posted by

Sure, here is a tutorial on how to search locations within a radius in MongoDB using Node.js:

Step 1: Install MongoDB and Node.js
Before we get started, make sure you have MongoDB and Node.js installed on your machine.

Step 2: Set up a MongoDB Database
Create a new MongoDB database and a collection for storing location data. You can do this by running the following commands in the MongoDB shell:

use mydb
db.createCollection("locations")

Step 3: Install the required Node.js packages
Next, create a new Node.js project and install the required packages using the following commands:

npm init -y
npm install express mongoose body-parser

Step 4: Create a Node.js script
Create a new JavaScript file (e.g., app.js) and add the following code to connect to the MongoDB database and define a schema for the location data:

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();

mongoose.connect('mongodb://localhost/mydb', { useNewUrlParser: true, useUnifiedTopology: true });
const Location = mongoose.model('Location', new mongoose.Schema({
  name: String,
  location: {
    type: {
      type: String,
      default: 'Point'
    },
    coordinates: [Number]
  }
}));

app.use(bodyParser.json());

app.post('/search', async (req, res) => {
  const { longitude, latitude, radius } = req.body;

  const locations = await Location.find({
    location: {
      $near: {
        $geometry: {
          type: "Point",
          coordinates: [parseFloat(longitude), parseFloat(latitude)]
        },
        $maxDistance: radius * 1000
      }
    }
  });

  res.json(locations);
});

app.listen(3000, () => console.log('Server running on port 3000'));

Step 5: Test the search functionality
You can test the search functionality by sending a POST request to http://localhost:3000/search with the longitude, latitude, and radius parameters in the request body. Here’s an example using curl:

curl -X POST -H "Content-Type: application/json" -d '{"longitude": 10.0, "latitude": 20.0, "radius": 5}' http://localhost:3000/search

This will return a list of locations within the specified radius of the given coordinates.

That’s it! You have successfully implemented a search functionality for locations within a radius in MongoDB using Node.js. #CodeWithNaf