Geolocation Search Based on Lat Long Using Nodejs Mongodb

How to search based on latlong in nodejs and mongodb#

In this blog we will discuss about searching users based on their geolocation (latitude and logitude).

Suppose you have users collection in your mongodb and you want to search users in certain radius then you have to create a index on that latitude and longitude.

Mongodb have inbuilt index for geosearch like 2d and 2dsphere. we are going to use 2dsphere index.

for creating proper schema of users with 2dsphere use the below code.

i hope you are using mongoose package to handle mongodb.

we will create a location property with type and coordinates data like below


    location: {
        type: {
            type: String,
            enum: ['Point'],

        },
        coordinates: {
            type: [Number],
            required: true
        }

    },

the complete user model Users.js schema of user will look like below


const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({

        username: { type: String, index: true, unique: true },
        first_name: { type: String, },
        last_name: { type: String, },
        email: { type: String, unique: true, index: true, },

        location: {
            type: {
                type: String,
                enum: ['Point'],

            },
            coordinates: {
                type: [Number],
                required: true
            }

        },
    });
    // add index to location column

    userSchema.index({ location: "2dsphere" });

    const UserModel = mongoose.model('Users', userSchema);
    module.exports = UserModel


creating new user in mongodb#

we can use UserModel for creating new record into the mongodb like below SignupController.js

const UserModel = require('../mongo/models/Users');

exports.createUser = async function(req ,res) {

const user = new UserModel(
    { 
        username: "AbcUser",
        first_name: "John",
        last_name: "Doe",
        email: "abc@example.com",

        location: 
        {
                type: 'Point',
                coordinates: [-122.566656,72.455656]
                //  make sure that longitude should be first and then latitude
        }
    });

   try {
            await user.save()
            res.status(200).json({ "result": 'success',"user": user })
        } catch (err) {
            console.log(err);
            res.status(404).json({ "err": err })
        }

}

This will create a new user data in mongodb user collection .

for searching based on user latitude in certain radius use the below code.


const UserModel = require('../mongo/models/Users');

exports.searchEmployee = async function (req, res) {

    var latitude = req.query.latitude
    var longitude = req.query.longitude    
    

    try {

        var users = await UserModel.find(
            {
                location:
                {
                    $near:
                    {
                        $geometry: { type: "Point", coordinates: [longitude, latitude] },
                        $maxDistance: 500, // distance is in meters

                    }
                },
                
            }
        );
        return res.status(200).json({ msg: "success", users: users });
    } catch (error) {

         return res.status(500).json({ msg: "success", err: error });   
    
    }

   
    

}


comments powered by Disqus