express.js 链接数据库

在Express.js中链接数据库通常取决于你选择的数据库类型。最常见的数据库类型包括关系型数据库(如MySQL, PostgreSQL)和非关系型数据库(如MongoDB)。下面我将分别介绍如何在Express.js项目中链接这两种类型的数据库。

1. 链接MySQL或PostgreSQL数据库

对于MySQL或PostgreSQL这样的关系型数据库,你可以使用mysqlpg(对于PostgreSQL)这样的npm包来链接数据库。这里以mysql为例:

首先,你需要安装mysql包:

bash 复制代码
npm install mysql

然后,在你的Express.js应用中,你可以这样设置数据库连接:

javascript 复制代码
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

bash 复制代码
npm install mongoose

然后,在你的Express.js应用中设置MongoDB连接:

javascript 复制代码
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数据库的基本方法。根据你的具体需求,你可能需要调整数据库连接配置或查询逻辑。

相关推荐
像素之间9 分钟前
为什么运行时要加set NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve
前端·javascript·vue.js
城数派11 分钟前
2000-2025年我国省市县三级逐8天日间地表温度数据(Shp/Excel格式)
数据库·arcgis·信息可视化·数据分析·excel
M ? A12 分钟前
Vue转React实战:defineProps精准迁移实战
前端·javascript·vue.js·经验分享·react.js·开源·vureact
AC赳赳老秦15 分钟前
OpenClaw text-translate技能:多语言批量翻译,解决跨境工作沟通难题
大数据·运维·数据库·人工智能·python·deepseek·openclaw
如意猴25 分钟前
【前端】002--怎样制作一个简历界面?
开发语言·前端·javascript
AI应用实战 | RE31 分钟前
014、索引高级实战:当单一向量库不够用的时候
数据库·人工智能·langchain
ffqws_31 分钟前
Spring Boot入门:通过简单的注册功能串联Controller,Service,Mapper。(含有数据库建立,连接,及一些关键注解的讲解)
数据库·spring boot·后端
comerzhang65536 分钟前
手撕 V8:我是如何用 2.67ms 的心跳活捉 700ms 冻结幽灵的
javascript
im_AMBER37 分钟前
手撕发布订阅与观察者模式:从原理到实践
前端·javascript·面试
清水白石00843 分钟前
《Python 架构师的自动化哲学:从基础语法到企业级作业调度系统与 Airflow 止损实战》
数据库·python·自动化