我正在node.js中构建一个公交订票应用程序。我已经创建了4个表。1 -用户表,2 -公交表,3 -订票表,4 -线路表。
下面是行程模型:
const routeSchema = new mongoose.Schema({
departureLocation: {
name: {
type: String,
required: true,
},
subLocation: { type: [String] },
time: {
type: String,
required: true
}
},
arrivalLocation: {
name: {
type: String,
required: true,
},
subLocation: { type: [String] },
time : {
type: String,
required: true
}
},
duration: {
type: Number,
required: true,
},
busId:{
type: mongoose.Schema.Types.ObjectId,
ref:"Bus",
required: true
},
date: {
type:String,
required: true
},
},
{
timestamps: true,
});
在该行程模型中,只有管理员(经过身份验证的用户)可以添加有关行程的数据(如出发位置、到达位置、公交数据和日期)
router.post("/addTrip", auth, async (req, res) => {
const route = new Route(req.body);
try {
await route.save();
res.status(201).send(route);
} catch (e) {
res.status(500).send();
}
});
假设有搜索框供用户输入像这样的旅行细节
https://i.stack.imgur.com/oXvsj.png
用户输入数据并将数据转换为查询字符串(如:127.0.0.1:3000/trips?出发=surat&到达=bhavnagar&date=2022-05-30),基于该查询字符串,我想向用户显示所有匹配的旅行。
现在我想根据用户(未经身份验证的用户)需要过滤数据,但我不知道如何做到这一点。
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"})
}
let departure = req.query.departure;
let arrival = req.query.arrival;
let date = req.query.date;
let routes = await Route.find().lean().exec();
let route = routes.find((route) => {
route.departureLocation.name.toLowerCase() == departure &&
route.arrivalLocation.name.toLowerCase() == arrival &&
route.date == date;
//What to write here
});
})
我已经在公交车模型中嵌入了座位数据
const busSchema = new mongoose.Schema(
{
busNumber: {
type: String,
unique: true,
required: true,
},
seats: {
type: Number,
required: true
},
},
{
timestamps: true,
}
);
如何向用户显示匹配行程的公共汽车和座位
您可以使用find
函数对数据进行filter
:
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',
});
}
let departure = req.query.departure;
let arrival = req.query.arrival;
let date = req.query.date;
let routes = await Route.find({
departureLocation: departure,
arrivalLocation: arrival,
date
}).lean().exec();
return res.status(200).json(routes);
});