I am building bus ticket booking app in node.js In this app I have created different tables like location table, route table and others
My location schema lokks like this.
const locationSchema = new mongoose.Schema(
{
departureLocation: {
name: {
type: String,
required: true,
},
time: {
type: String,
required: true,
},
subLocations: { type: [String] },
},
arrivalLocation: {
name: {
type: String,
required: true,
},
time: {
type: String,
required: true,
},
subLocations: { type: [String] },
},
},
{
timestamps: true,
}
);
In this table only administrator can enter data about locations. after inserting data to location table my mongodb location table looks like this. https://i.stack.imgur.com/Bbt8S.png After entering data about location only admin can add data about trips(routes) route schema looks like this
const routeSchema = new mongoose.Schema({
location:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Location',
required: true
},
duration: {
type: Number,
required: true,
},
busId:{
type: mongoose.Schema.Types.ObjectId,
ref:"Bus",
required: true
},
date: {
type:String,
required: true
},
},
{
timestamps: true,
});
The route table looks like this https://i.stack.imgur.com/UamRi.png I am referencing location id table to location schema
But the problem starts now on I want to show only matched results they enter in query string like:(http://127.0.0.1:3000/trips?departure=surat&arrival=bhavnagar&date=2022-05-30) all users (general users) but the problem is that I am getting all the results from the database
my get request is this:
router.get("/trips", async (req, res) => {
if ((!req.query.departure && !req.query.arrival) || !req.query.date) {
return res.send({
error: "Please enter the data to get the trip",
});
}
const { departure, arrival, date } = req.query;
const locations = await Location.find({
'departureLocation.name': departure,
'arrivalLocation.name': arrival
})
const routes = await Route.find({
locations,
date
});
return !routes ? res.status(404).send() : res.status(200).send(routes);
});
I think it is only parsing the date but it skips the other parameters from query string. I know something's wrong in the code but don't know where?
CodePudding user response:
You should use the ids of locations in the Route.find
with $in
operator like this:
const ids = locations.map(l => l._id);
const routes = await Route.find({
$and: [
{ location: { $in: ids }},
{ date },
]
});
Also make sure the Location.find
returns the locations you expect. So try console.log(locations)
before Route.find