引言:为什么开发者需要了解 SQL 和 NoSQL?
现代 JavaScript (Node.js) Web 开发几乎离不开与数据库的交互。在关系型 (PostgreSQL) 和文档型 (MongoDB) 数据库管理系统之间做出选择,是一项关键的架构决策。本文将通过实践,讲解如何连接这两种数据库、执行 CRUD 操作,以及如何针对具体任务选择合适的工具。
我们将使用流行的库:用于 PostgreSQL 的 pg 和用于 MongoDB 的 mongoose。所有代码示例均基于 Node.js。
1. Node.js 中的 PostgreSQL:关系型方法
1.1. 连接与配置
PostgreSQL 是一款功能强大的关系型数据库管理系统,支持 SQL。要在 Node.js 中使用它,请安装 pg 包:
npm install pg连接到本地数据库 mydb 的示例:
const { Pool } = require('pg');
const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'mydb', password: 'secret', port: 5432,});
// 测试连接pool.query('SELECT NOW()', (err, res) => { if (err) { console.error('连接错误:', err); } else { console.log('已连接到 PostgreSQL:', res.rows[0].now); }});1.2. CRUD 操作(创建、读取、更新、删除)
创建一个 users 表并执行基本操作。
创建表:
const createTable = async () => { const query = ` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, age INTEGER ); `; await pool.query(query); console.log('users 表已创建');};
createTable();插入数据 (INSERT):
const addUser = async (name, email, age) => { const query = 'INSERT INTO users (name, email, age) VALUES ($1, $2, $3) RETURNING *'; const values = [name, email, age]; const res = await pool.query(query, values); console.log('已添加用户:', res.rows[0]);};
addUser('伊万·彼得罗夫', 'ivan@example.com', 30);读取数据 (SELECT):
const getUsers = async () => { const res = await pool.query('SELECT * FROM users'); console.log('所有用户:', res.rows);};
getUsers();更新数据 (UPDATE):
const updateUserAge = async (id, newAge) => { const query = 'UPDATE users SET age = $1 WHERE id = $2 RETURNING *'; const values = [newAge, id]; const res = await pool.query(query, values); console.log('已更新用户:', res.rows[0]);};
updateUserAge(1, 31);删除数据 (DELETE):
const deleteUser = async (id) => { const query = 'DELETE FROM users WHERE id = $1 RETURNING *'; const values = [id]; const res = await pool.query(query, values); console.log('已删除用户:', res.rows[0]);};
deleteUser(1);请注意使用参数化查询 ($1, $2)。这可以防止 SQL 注入攻击。
1.3. 何时选择 PostgreSQL?
- 需要严格的数据结构和完整性支持(外键、事务)。
- 需要复杂的 JOIN 查询和聚合操作。
- 处理财务或关键业务数据。
- 项目使用 Sequelize 或 TypeORM 等 ORM 框架。
2. Node.js 中的 MongoDB:NoSQL 的灵活性
2.1. 通过 Mongoose 连接
MongoDB 是一种文档型数据库,数据以 JSON-like (BSON) 格式存储。使用时请安装 mongoose:
npm install mongoose连接到本地 Mo