Home > Blockchain >  How to find documents based on the result of a function mongoose
How to find documents based on the result of a function mongoose

Time:05-06

So I have two schemas user and driver they both have latitude and longitude attributes.

At some point I want to query the database for nearby drivers, I will be sending the user's current location (latitude and longitude) and I have a function to calculate the distance between two points.

I am trying to do something like this:

find all drivers with distance less than 2 KM using my function ( the function is called calculateDistance).

In code this will be like this:

const drivers = await Driver.find();

const driversToReturn = drivers.filter(
    driver => calculateDistance(userLat, userLong, driver.latitude, driver.longitude) <= 2
);

res.status(200).json({
  drivers: driversToReturn
});

but I don't think this is the best way to do it, I've checked the mongoose virtuals but we can't pass params (userLat and userLong) to the get method of a virtual and I don't think instance methods are the solution.

so how should I do this?

Thanks

EDIT

Driver Model

const mongoose = require("mongoose");
const { Schema } = mongoose;

const driverSchema = new Schema(
  {
    /** Required Attributes */
    name: { type: String, required: true },
    carBrand: { type: String, required: true },
    plateNumber: { type: String, required: true },
    password: { type: String, required: true },
    phoneNumber: { type: Number, required: true },
    price: { type: Number, required: true },
    latitude: { type: Number, required: true },
    longitude: { type: Number, required: true },

    /** Not Required Attributes */
    rating: { type: Number, required: false },
  },
  {
    timestamps: true,
  }
);

const Driver = mongoose.model("Driver", driverSchema);

module.exports = Driver;

User Model

const mongoose = require("mongoose");
const { Schema } = mongoose;

const userSchema = new Schema(
  {
    /** Required Attributes */
    name: { type: String, required: true },
    password: { type: String, required: true },
    phoneNumber: { type: Number, required: true },
    latitude: { type: Number, required: true },
    longitude: { type: Number, required: true },
  },
  { timestamps: true }
);

const User = mongoose.model("User", userSchema);

module.exports = User;

Users Controller

const Driver = require("../models/driver");
const Order = require("../models/order");
const calculateDistance = require("../utils/calculateDistance");

const CIRCLE_RADIUS_IN_KM = 2;

exports.getNearbyDrivers = async (req, res, next) => {
  try {
    const userLat = req.body.userLat,
        userLong = req.body.userLong,
        drivers = await Driver.find();

    const driversToReturn = drivers.filter(
        (driver) =>
            calculateDistance(
                userLat,
                userLong,
                driver.latitude,
                driver.longitude
            ) <= CIRCLE_RADIUS_IN_KM
    );

    res.status(200).json({
      drivers: driversToReturn,
    });
  } catch (err) {
    if (!err.statusCode) {
      err.statusCode = 500;
    }

    next(err);
  }
};

CodePudding user response:

Here is some code from the documentation of Mongoose that can help you with that I think :

    const denver = { type: 'Point', coordinates: [-104.9903, 39.7392] };
    return City.create({ name: 'Denver', location: denver }).
      then(() => City.findOne().where('location').within(colorado)).
      then(doc => assert.equal(doc.name, 'Denver'));

and here is the link : https://mongoosejs.com/docs/geojson.html

  • Related