在之前的学习中,我们使用了Restful
API的模式,将数据的操作放到了单独的文件夹中,路由也放在了单独的文件夹。
这次我们尝试使用mongoose
的Model
模型来管理数据库的数据,使用模型的一大好处就是可以约束数据的结构,从而使数据相对来说更加规范和安全。
在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'); })
|
这是一个基本的示例程序,我们通过mongoose
API连接了数据库,并用mongoose.model('xxx', new mongoose.Schema({}))
定义了一个数据库的模型对象,通过这个对象能够直接对数据库进行规范的操作。