MongoDB 安装
在mongodb 官网 选择自己的操作系统下载
下载完成解压后重命名为 mongodb
配置环境变量
export PATH=/usr/local/mongodb/bin:$PATH
在 mongodb 根目录下新建数据库存储目录 /data/db
然后启动 mongod
启动成功后 再打开一个终端输入 mongo
即可启动服务
MongoDB 连接
安装 mongoose
包
npm i mongoose
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/express-test', { useNewUrlParser: true, useUnifiedTopology: true })
const Product = mongoose.model('Product', new mongoose.Schema({ title: String }))
Product.insertMany([ { title: '测试产品1' }, { title: '测试产品2' }, ])
app.get('/product', async (req, res) => { res.send(await Product.find()) })
|
MongoDB 查询
Product.find()
: 查询所有的数据
Product.find().limit(2)
: 限制条数 只返回2条数据
Product.find().skip(1).limit(2)
: 跳过第一条数据,返回后面两条数据 (用于做分页)
Product.find().where({ title: '产品1' })
: 添加条件参数来 查询数据
Product.find().sort({ _id: 1 })
: 排序 1是正序 -1是倒序
1 2 3 4 5 6 7 8 9 10 11 12 13
| app.get('/product', async (req, res) => { const data = await Product.find(); res.send(data); }
app.get('/product/:id', async (req, res) => { const data = await Product.findById(req.params.id); res.send(data) })
|
MongoDB 新增产品和POST请求
新增产品
1 2 3 4 5 6 7 8
| app.post('/product', async (req, res) => { const data = req.body;
const product = await Product.create(data); res.send(product); })
|
POST请求
首先在 vscode
安装 REST Client
插件
REST Client
: 用来测试接口数据的工具 类似于 Postman
在项目根目录中新建 test.http
文件
###
: 代表结束符
点击 Send Request
即可在 vscode
右侧窗口看到执行的结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @uri=http:
Send Request GET {{uri}}product
###
Send Request POST {{uri}}product Content-Type: application/json
{ "title": "产品1" }
###
|
1 2 3 4 5 6 7 8 9
|
{ "_id": "5e80bdb9f42f1f90b2f60941", "title": "产品1", "__v": 0 }
|
MongoDB 修改产品 和 PUT请求
1 2 3 4 5 6 7 8 9 10 11 12
| app.put('/product/:id', async (req, res) => { const product = await Product.findById(req.params.id);
product.title = req.body.title;
await product.save() res.send(product); })
|
那么如何测试接口呢
还是使用之前的 REST Client
插件
修改请求方式为 PUT
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
PUT {{uri}}product/5e80a84e1ac6f88cf68f268d
Content-Type: application/json
{ "title": "产品666" }
HTTP/1.1 200 OK X-Powered-By: Express Access-Control-Allow-Origin: * Content-Type: application/json; charset=utf-8 Content-Length: 62 ETag: W/"3e-71mz7eph3NU5pIezQ9R97V5S0ww" Date: Mon, 30 Mar 2020 14:25:37 GMT Connection: close
{ "_id": "5e80a84e1ac6f88cf68f268d", "title": "产品666", "__v": 0 }
|
MongoDB 删除产品 和 DELETE 请求
删除产品
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| app.delete('/product/:id', async (req, res) => { const product = await Product.findById(req.params.id); await product.delete();
const product = await Product.findById(req.params.id); await product.remove();
await Product.deleteOne({ _id: req.params.id })
res.send({ success: true }) })
|
DELETE 请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| DELETE {{uri}}product/5e80bd55485cfa9080fa4585
HTTP/1.1 200 OK X-Powered-By: Express Access-Control-Allow-Origin: * Content-Type: application/json; charset=utf-8 Content-Length: 16 ETag: W/"10-oV4hJxRVSENxc/wX8+mA4/Pe4tA" Date: Mon, 30 Mar 2020 15:04:36 GMT Connection: close
{ "success": true }
|
实例完整代码
静态文件 index.html
1 2 3 4 5 6 7 8 9
| <body> <h1>express 访问静态文件</h1> <script> fetch('http://localhost:3000/product').then(res => res.json()).then(res =>{ console.log(res); }) </script> </body>
|
接口文件 index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
const express = require('express');
const app = express();
app.use(require('cors')());
app.use(express.static('public'))
app.use(express.json())
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/express-test', { useNewUrlParser: true, useUnifiedTopology: true })
const Product = mongoose.model('Product', new mongoose.Schema({ title: String }))
app.get('/about', (req, res) => { res.send({ 'page': 'about' }) })
app.get('/product', async (req, res) => { res.send(await Product.find()) })
app.get('/product/:id', async (req, res) => { const data = await Product.findById(req.params.id); res.send(data) })
app.post('/product', async (req, res) => { const data = req.body; const product = await Product.create(data); res.send(product); })
app.put('/product/:id', async (req, res) => { const product = await Product.findById(req.params.id); product.title = req.body.title; await product.save() res.send(product); })
app.delete('/product/:id', async (req, res) => { await Product.deleteOne({ _id: req.params.id }) res.send({ success: true }) })
app.listen(3000, () => { console.log('serve port is 3000!'); })
|
测试接口文件 test.http
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
@uri=http:
GET {{uri}}product
###
GET {{uri}}product/5e80a84e1ac6f88cf68f268d
###
POST {{uri}}product Content-Type: application/json
{ "title": "产品1" }
###
PUT {{uri}}product/5e80a84e1ac6f88cf68f268d Content-Type: application/json
{ "title": "产品666" }
###
DELETE {{uri}}product/5e80bd55485cfa9080fa4585
|