Assign a delivery to the nearest available driver

 Great — you already have clean Mongoose models! To assign a delivery to the nearest available driver, you'll implement a geo-based query on the Driver collection to find a driver close to the restaurant’s location and available.


✅ Step-by-Step Logic

1. Get the Restaurant Location

From the Restaurant model:

js
const restaurant = await Restaurant.findById(restaurantId); const { lat, lng } = restaurant.address.coordinates;

2. Find the Nearest Available Driver

You can use MongoDB's geoNear feature if you convert currentLocation into a 2dsphere index:

🛠 Modify Driver model:

js
driverSchema.index({ currentLocation: "2dsphere" });

✅ This lets MongoDB understand lat/lng for spatial queries.


3. Query for Nearby Available Drivers

js
const nearbyDrivers = await Driver.find({ status: 'available', currentLocation: { $near: { $geometry: { type: "Point", coordinates: [lng, lat], // Mongo expects [lng, lat] }, $maxDistance: 5000 // meters = 5 km } } }).limit(1); // Pick the closest one

You can adjust maxDistance using restaurant.deliveryRadius * 1000.


4. Assign Delivery to the Driver

js
if (nearbyDrivers.length > 0) { const driver = nearbyDrivers[0]; const newDelivery = new Delivery({ orderId, driverId: driver.driverId, pickupLocation: `${restaurant.address.street}, ${restaurant.address.city}`, deliveryLocation: customerAddress, assignedAt: new Date() }); await newDelivery.save(); // Update driver status to "busy" driver.status = "busy"; await driver.save(); return res.status(200).json({ message: "Delivery assigned", driver }); } else { return res.status(404).json({ message: "No available drivers nearby" }); }

🔄 Summary Flow

  1. Get restaurant coordinates.

  2. Query MongoDB for the closest driver within radius.

  3. Create a new Delivery record with driver info.

  4. Update driver status.

  5. Done 🎉


⚠️ Important Notes

  • MongoDB geo queries require 2dsphere index.

  • MongoDB uses [lng, lat] (reverse order from usual).

  • Always check driver availability before assigning.

  • Optional: Implement a retry or queue if no drivers are found.


Want this wrapped as an Express route or want me to write a reusable service function?

Comments

Popular posts from this blog

Use the Google Custom Search JSON API to retrieve images

How to Check for NVIDIA GPU and Set It Up in Ubuntu

Development-Testing Workflow