在Express.js中链接数据库通常取决于你选择的数据库类型。最常见的数据库类型包括关系型数据库(如MySQL, PostgreSQL)和非关系型数据库(如MongoDB)。下面我将分别介绍如何在Express.js项目中链接这两种类型的数据库。
1. 链接MySQL或PostgreSQL数据库
对于MySQL或PostgreSQL这样的关系型数据库,你可以使用mysql
或pg
(对于PostgreSQL)这样的npm包来链接数据库。这里以mysql
为例:
首先,你需要安装mysql
包:
npm install mysql
然后,在你的Express.js应用中,你可以这样设置数据库连接:
const express = require('express');
const mysql = require('mysql');const app = express();
const PORT = 3000;// 数据库配置
const db = mysql.createConnection({host : 'localhost',user : 'yourUsername',password : 'yourPassword',database : 'yourDatabase'
});// 连接到数据库
db.connect(err => {if (err) {return console.error('error: ' + err.message);}console.log('Connected to the MySQL server.');
});// 示例路由
app.get('/', (req, res) => {db.query('SELECT * FROM yourTable', (err, results, fields) => {if (err) throw err;res.send(results);});
});app.listen(PORT, () => {console.log(`Server running on port ${PORT}`);
});// 优雅关闭数据库连接
process.on('SIGINT', () => {db.end(() => {console.log('MySQL connection is closed');});
});
2. 链接MongoDB数据库
对于MongoDB这样的非关系型数据库,你可以使用mongoose
这样的npm包来链接数据库。mongoose
提供了丰富的模型(Model)和文档(Document)操作功能。
首先,安装mongoose
:
npm install mongoose
然后,在你的Express.js应用中设置MongoDB连接:
const express = require('express');
const mongoose = require('mongoose');const app = express();
const PORT = 3000;// MongoDB连接配置
mongoose.connect('mongodb://localhost:27017/yourDatabase', {useNewUrlParser: true,useUnifiedTopology: true
})
.then(() => console.log('MongoDB connected...'))
.catch(err => console.log(err));// 示例模型
const yourSchema = new mongoose.Schema({name: String,age: Number
});const YourModel = mongoose.model('YourModel', yourSchema);// 示例路由
app.get('/', async (req, res) => {try {const items = await YourModel.find();res.send(items);} catch (err) {res.status(500).send(err);}
});app.listen(PORT, () => {console.log(`Server running on port ${PORT}`);
});
注意:在上面的MongoDB示例中,我使用了async/await
来处理异步操作,这是ES7引入的特性,它使得异步代码看起来和同步代码一样。确保你的Node.js版本支持async/await
(Node.js 7.6+)。
以上就是在Express.js中链接MySQL/PostgreSQL和MongoDB数据库的基本方法。根据你的具体需求,你可能需要调整数据库连接配置或查询逻辑。