安装

mongodb 官网
mongodb 中文官网

node 实例: 使用 express 和 mongoose 实现简单的文章管理 API

初始化项目

1
npm init -y

依赖安装

1
npm i express@latest cors mongoose

数据建模

1
2
3
4
5
6
7
8
import mongoose from "mongoose"

const Article = mongoose.model(
"Article",
new mongoose.Schema({
title: { type: String },
})
)

增删改查 API 实现

1
2
3
4
5
6
7
8
app.get("/articles", async (req, res) => {
const article = await Article.find()
res.send({
success: true,
message: "get article list",
data: article,
})
})
1
2
3
4
5
6
7
8
9
app.get("/articles/:id", async (req, res) => {
const id = req.params.id
const article = await Article.findById(id)
res.send({
success: true,
message: "get article by id",
data: article,
})
})
1
2
3
4
5
6
7
8
9
10
11
12
13
app.post("/articles", async (req, res) => {
const body = req.body

const article = await Article.create({
title: body.title,
})

res.send({
success: true,
message: "create article",
data: article,
})
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
app.put("/articles/:id", async (req, res) => {
const id = req.params.id
const body = req.body

const article = await Article.findById(id)
article.title = body.title
await article.save()

res.send({
success: true,
message: "update article",
data: article,
})
})
1
2
3
4
5
6
7
8
9
10
11
12
13
app.delete("/articles/:id", async (req, res) => {
const id = req.params.id
await Article.deleteOne({ _id: id })

// 或者可以使用以下方法进行删除
// const article = await Article.findById(id)
// await article.remove()

res.send({
success: true,
message: "delete article",
})
})
完整代码
main.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
71
72
73
74
75
76
77
78
79
80
81
82
import express from "express"
import mongoose from "mongoose"
import cors from "cors"

const app = express()
app.use(express.json())
app.use(cors())

try {
await mongoose.connect("mongodb://127.0.0.1:27017/mongodb-test")
} catch (error) {
console.error("error:数据库连接失败\n", error)
}

const Article = mongoose.model(
"Article",
new mongoose.Schema({
title: { type: String },
})
)

app.get("/articles", async (req, res) => {
const article = await Article.find()
res.send({
success: true,
message: "get article list",
data: article,
})
})

app.get("/articles/:id", async (req, res) => {
const id = req.params.id
const article = await Article.findById(id)
res.send({
success: true,
message: "get article by id",
data: article,
})
})

app.post("/articles", async (req, res) => {
const body = req.body

const article = await Article.create({
title: body.title,
})

res.send({
success: true,
message: "create article",
data: article,
})
})

app.put("/articles/:id", async (req, res) => {
const id = req.params.id
const body = req.body

const article = await Article.findById(id)
article.title = body.title
await article.save()

res.send({
success: true,
message: "update article",
data: article,
})
})

app.delete("/articles/:id", async (req, res) => {
const id = req.params.id
await Article.deleteOne({ _id: id })
res.send({
success: true,
message: "delete article",
})
})

const port = 3000
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})

查看运行情况

可以使用 vscode 插件 rest client 来测试接口运行情况,以下是我本地接口测试文件。如果你要在本地测试,可以将 66ae4047563fa3933c1b38ba 改成真实的查询列表里的某一个文章的 id 即可

说明

rest client 这个插件在我的博客里有介绍,可以移步 rest client 插件使用 了解其基础使用方法

测试代码
articles.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
@uri=http://localhost:3000

### 获取文章列表
GET {{uri}}/articles

### 创建文章
POST {{uri}}/articles
Content-Type: application/json

{
"title": "添加文章标题"
}

### 根据id获取文章
GET {{uri}}/articles/66ae4047563fa3933c1b38ba

### 编辑文章
PUT {{uri}}/articles/66ae4047563fa3933c1b38ba
Content-Type: application/json

{
"title": "编辑文章标题"
}

### 删除文章
DELETE {{uri}}/articles/66ae4047563fa3933c1b38ba