I am working on a cab booking api. The issue i am facing on is a getAllBookings api which will be used by admin to get the history of all the bookings from booking database. Speaking of database, i shall share the database model for my booking model and user model in a bit. The issue i am facing is, when i make a search query using the userId or driverId in params i get the response properly along with all the details with that particular id. However, when i try to send name query or email query in params for the same user of that userId, it returns an empty bookings array. Following is my Booking model:
const mongoose = require('mongoose');
const bookingSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
driver: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
pickupLocation: {
address: {
type: String,
required: true
},
latitude: {
type: Number
},
longitude: {
type: Number
},
},
dropoffLocation: {
address: {
type: String,
required: true,
},
latitude: {
type: Number,
},
longitude: {
type: Number,
},
},
fare: {
type: Number,
required: true,
},
bookingStatus: {
type: String,
required: true,
default: 'Available',
}
},
{
timestamps: true
});
module.exports = mongoose.model("Booking", bookingSchema);
User model:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Please add your Name"],
trim: true
},
email: {
type: String,
required: [true, "Please add the user email address"],
unique: [true,"Email address already taken"],
trim: true
},
password: {
type: String,
required: [true, "Please add the password"],
trim: true,
},
phoneNumber: {
type: String,
required: [true, "Please add Phone Number"],
trim: true
},
role: {
type: String,
required: true,
default: 'user',
enum: ['admin', 'user', 'driver'],
},
licenseNumber: {
type: String,
trim: true
},
carModel: {
type: String,
trim: true
},
carNumber: {
type: String,
trim: true
},
isDeleted: {
type: Boolean,
default: false
},
isAvailable: {
type: Boolean,
default: false
},
location: {
type: {
type: String,
enum: ['Point']
},
coordinates: {
type: [Number] //lat and long
}
},
},
{
timestamps: true
});
// Index the location field for geospatial queries
userSchema.index({ location: '2dsphere' });
module.exports = mongoose.model("User", userSchema);
And here is the controller function for your referrence:
const getAllBookings = async(req, res) => {
logger.info('Inside getAllBookings');
try{
const {
page = 1,
limit = 10,
name,
email,
role,
userId,
driverId,
} = req.query;
let filter = {};
if (name) {
filter['user.name'] = { $regex: name, $options: 'i' };
}
if (email) {
filter['user.email'] = { $regex: email, $options: 'i' };
}
if(role){
filter['user.role'] = role;
}
if(userId){
filter.user = userId;
}
if(driverId){
filter.driver = driverId;
}
const skip = (page - 1) * limit;
console.log(filter);
const bookings = await Booking.find(filter)
.populate('user driver')
.skip(skip)
.limit(limit)
.sort({createdAt: -1})
.lean()
.exec();
console.log("bookings", bookings);
const count = await Booking.countDocuments(filter);
const totalPages = Math.ceil(count / limit);
res.status(200).json({bookings, totalPages, currentPage: +page});
} catch(error){
logger.error(`Error in getAllBookings: ${error.message}`);
res.status(500).json({
message: 'Server Error',
});
}
};
This is the postman response when an id is sent in query params | This is the postman response when the name of the user with the above id is sent in query params | As you can see it only gives results when the id is passed. Please assist me to debug this because i want it to be functional when name or email is sent as well.
I tried to debug it by consoling some lines. But still i was not able to figure out the issue