我正在 node.js 中構建巴士票預訂應用程式在這個應用程式中,我創建了不同的表,如位置表、路線表等
我的位置模式是這樣的。
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,
}
);
在此表中,只有管理員可以輸入有關位置的資料。將資料插入位置表后,我的 mongodb 位置表如下所示。 https://i.stack.imgur.com/Bbt8S.png 輸入有關位置的資料后,只有管理員可以添加有關旅行(路線)的資料,路線架構如下所示
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,
});
路由表看起來像這樣 https://i.stack.imgur.com/UamRi.png 我將位置 id 表參考到位置模式
但是問題從現在開始,我只想顯示他們在查詢字串中輸入的匹配結果,例如:(http://127.0.0.1:3000/trips?departure=surat&arrival=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",
});
}
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);
});
我認為它只是決議日期,但它會跳過查詢字串中的其他引數。我知道代碼有問題但不知道在哪里?
uj5u.com熱心網友回復:
Route.find
您應該使用with運算子中的位置 ID,$in
如下所示:
const ids = locations.map(l => l._id);
const routes = await Route.find({
$and: [
{ location: { $in: ids }},
{ date },
]
});
還要確保Location.find
回傳您期望的位置。console.log(locations)
所以先試試Route.find
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/481702.html
下一篇:返回列表