I want to get all matched data from an object but I am getting an empty array.
Here is the location table:
const locationSchema = new mongoose.Schema(
{
location: {
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
subLocation: [String],
},
},
{
timestamps: true,
}
);
and it is embedded in route table:
const routeSchema = new mongoose.Schema(
{
location: {
from: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
to: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
},
busId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Bus",
required: true,
},
date: {
type: String,
required: true,
},
departureTime: {
type: Number,
required: true,
},
arrivalTime: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);
Now I am running query to get the matched data from route table but I am getting an empty array.
http://127.0.0.1:3000/trips?from=6295871d69217e9c28cf7f19&to=6295874869217e9c28cf7f1c&date=2022-06-02
here is the query :
router.get("/trips", async (req, res) => {
if (!req.query.from || !req.query.to || !req.query.date) {
return res.send({
error: "Please enter the data to get the trip",
});
}
const { from, to, date } = req.query;
const routes = await Route.find({
from,
to,
date,
});
Another Question:
I am passing an Id as a value now I want to pass value as a sting like this: from=Mumbai&to=Ahmedabad&date=2022-06-02.
How to do that? because whenever I do that I am getting a casting error
I suggest you to change the location schema to have from and to locations separately like below.
const locationSchema = new mongoose.Schema(
{
fromLocation: {
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
subLocation: [String],
},
toLocation: {
name: {
type: String,
unique: true,
required: true,
lowercase: true,
},
subLocation: [String],
},
},
{
timestamps: true,
}
);
Thus the route schema should look like this
const routeSchema = new mongoose.Schema(
{
location: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
date: {
type:String,
required: true
},
....
....
And then do something like this...
let locations = await Location.find({
'fromLocation.name': from,
'toLocation.name': to,
});
After that
const ids = locations.map(location => location._id)
const routes = await Route.find({$and: [{location : {$in: ids}},{date}]});
const route = routes.find(()=>{
return ([{ date }, { routes }])
});