iT邦幫忙

2023 iThome 鐵人賽

DAY 20
0
自我挑戰組

NodeJS with MongoDB專案開發系列 第 20

day 20 Mongo DB連動Node.js專案開發

  • 分享至 

  • xImage
  •  

Mongo DB作為後端寫一個等公車系統

我們可以將mongo db生活化,寫一個等公車系統用mongo db作為呈現
我們先安裝Node.js和MongoDB,然後創建一個新的Node.js項目,並安裝必要的庫:

npm init
npm install express mongoose

接下來,創建一個Express應用程序,設置MongoDB連接,定義模型和路由。

const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = process.env.PORT || 3000;

mongoose.connect('mongodb://localhost/bus_system', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const BusStop = mongoose.model('BusStop', {
  name: String,
  latitude: Number,
  longitude: Number
});

const BusRoute = mongoose.model('BusRoute', {
  name: String,
  stops: [{ type: mongoose.Schema.Types.ObjectId, ref: 'BusStop' }]
});

app.get('/bus_stops', async (req, res) => {
  try {
    const busStops = await BusStop.find();
    res.json(busStops);
  } catch (error) {
    res.status(500).json({ error: 'An error occurred' });
  }
});

app.get('/bus_routes', async (req, res) => {
  try {
    const busRoutes = await BusRoute.find().populate('stops');
    res.json(busRoutes);
  } catch (error) {
    res.status(500).json({ error: 'An error occurred' });
  }
});

app.get('/simulate_waiting_time/:stopId', (req, res) => {
  const stopId = req.params.stopId;
  const frequency = busFrequency[stopId];
  if (frequency) {
    const waitingTime = Math.floor(Math.random() * frequency);
    res.json({ stopId, waitingTime });
  } else {
    res.status(404).json({ error: 'Stop not found' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

在上面的程式中,我們使用Express創建了一個基本的Web服務器,並連接到MongoDB。我們定義了BusStopBusRoute模型,然後創建了三個路由:

  1. /bus_stops:檢索所有公車站點信息。
  2. /bus_routes:檢索所有公車路線信息,並使用populate方法填充站點數據。
  3. /simulate_waiting_time/:stopId:模擬等候時間,接受站點的ID並返回等候時間。

請注意,上述代碼中的busFrequency是一個假設的公車到達頻率數據。在實際應用中,您需要根據實際數據來計算等候時間。

最後,啟動您的Node.js應用程序:

node app.js

現在,您可以使用HTTP請求來訪問您的API,檢索公車站點信息,檢索公車路線信息並模擬等候時間。網站前端或移動應用程序可以使用這個API來實現等公車程式的功能。


上一篇
day 19 node.js with mongo db專案開發
下一篇
day 20 node.js with mongo db專案開發
系列文
NodeJS with MongoDB專案開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言