使用模型

Sy_ Lv6

在之前的学习中,我们使用了Restful API的模式,将数据的操作放到了单独的文件夹中,路由也放在了单独的文件夹。

这次我们尝试使用mongooseModel模型来管理数据库的数据,使用模型的一大好处就是可以约束数据的结构,从而使数据相对来说更加规范和安全。

node.js中原生支持了mongodb模块来操作mongodb数据库,这次我们使用mongoose模块,他是mongodb模块的一个封装,将很多操作化繁为简,并且直接支持模型的操作,非常方便。

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
const express = require('express')
const app = express()

// 连接数据库
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/element-admin')

// 定义文章模型
const Article = mongoose.model('Article', new mongoose.Schema({
title: {
type: String
},
content: {
type: String
}
}))

// 允许跨域
app.use(express.json())
app.use(require('cors')())

app.get('/', async (req, res) => {
res.send('index')
})

app.post('/api/posts/add', async (req, res) => {
const article = await Article.create(req.body)
res.send(article)
})

app.get('/api/posts/list', async (req, res) => {
const articles = await Article.find();
res.send(articles)
})

app.listen(3000, () => {
console.log('http://localhost:3000');
})

这是一个基本的示例程序,我们通过mongooseAPI连接了数据库,并用mongoose.model('xxx', new mongoose.Schema({}))定义了一个数据库的模型对象,通过这个对象能够直接对数据库进行规范的操作。

  • 标题: 使用模型
  • 作者: Sy_
  • 创建于 : 2025-06-15 00:51:35
  • 更新于 : 2025-06-15 00:51:35
  • 链接: https://shenying.online//demo/re171jfu/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
使用模型