mkdir mongodb-demo
cd mongodb-demo
code .
npm init -y
因為Express 是一個 Node.js 網路應用框架,透過它能快速建立簡單且可用的網頁伺服器。
npm install express -p
const express = require('express')
const app = express()
const PORT = 3000
app.listen(PORT, () => {
console.log(`App is running on http://localhost:${PORT}`)
})
npm install -g nodemon
nodemon app.js
app.get('/', (req, res) => {
res.status(200).send('OK')
})
npm install mongoose -p
mongoose.connect('mongodb://localhost/school', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const SchoolSchema = new mongoose.Schema({
name: String,
level: Number,
is_close: Boolean
})
const School = mongoose.model('school', SchoolSchema)
//async 和 await 使得寫異步代碼的過程更像是寫同步代碼
app.get('/', async (req, res) => {
const schools = await School.find({})
res.status(200).send(schools)
})
//新增資料的路由
app.post('/school', async (req, res) => {
await School.create({
name: '我的大學',
level: 0,
is_close: false
})
res.status(200).send('Create School Success')
})
app.delete('/school', async (req, res) => {
const { id } = req.query
await School.deleteOne({
_id: id
})
res.status(200).send('Delete' + id + 'School Success')
})
app.put('/school', async (req, res) => {
const { id, name, is_close } = req.query
await School.updateOne({ _id: id }, {
name,
is_close
})
res.status(200).send('Update_id' + id + 'School Success')
})