Assign a delivery to the nearest available driver
- Get link
- X
- Other Apps
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:
jsconst 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:
jsdriverSchema.index({ currentLocation: "2dsphere" });
✅ This lets MongoDB understand lat/lng for spatial queries.
3. Query for Nearby Available Drivers
jsconst 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
usingrestaurant.deliveryRadius * 1000
.
4. Assign Delivery to the Driver
jsif (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
-
Get restaurant coordinates.
-
Query MongoDB for the closest driver within radius.
-
Create a new
Delivery
record with driver info. -
Update driver status.
-
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?
- Get link
- X
- Other Apps
Comments
Post a Comment
What is your thought about this?