在 JavaScript (Node.js) 中处理数据库:面向初学者的 PostgreSQL 和 MongoDB
在开发基于 JavaScript (Node.js) 的 Web 应用程序时,几乎总是需要保存数据:用户、订单、文章或日志。为此,需要使用数据库 (DB)。在本指南中,我们将介绍两种最流行的系统:关系型 PostgreSQL 和文档型 MongoDB。您将学习如何从 Node.js 连接到它们并执行基本的 CRUD 操作(创建、读取、更新、删除)。
本文面向熟悉 JavaScript 基础的初级开发人员。所有代码示例都可以在您的项目中运行。
1. PostgreSQL:关系型数据库
PostgreSQL 是一个强大的 SQL 数据库,其中数据存储在具有严格字段类型的表中。为了在 Node.js 中使用它,我们将使用 pg 包。
1.1. 安装和连接
首先,通过 npm 安装该包:
npm install pg创建一个 db.js 文件并配置到本地数据库的连接:
const { Pool } = require('pg');
const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'mydb', password: 'password', port: 5432,});
module.exports = pool;1.2. 创建表和 CRUD 操作
首先,创建一个包含 id、name 和 email 字段的 users 表。然后执行所有基本操作。
const pool = require('./db');
// 创建表async function createTable() { await pool.query(` CREATE TABLE IF NOT EXISTS users ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL ); `); console.log('表 users 已创建');}
// 插入数据 (CREATE)async function addUser(name, email) { const result = await pool.query( 'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *', [name, email] ); return result.rows[0];}
// 读取数据 (READ)async function getUsers() { const result = await pool.query('SELECT * FROM users'); return result.rows;}
// 更新数据 (UPDATE)async function updateUser(id, name) { const result = await pool.query( 'UPDATE users SET name = $1 WHERE id = $2 RETURNING *', [name, id] ); return result.rows[0];}
// 删除数据 (DELETE)async function deleteUser(id) { await pool.query('DELETE FROM users WHERE id = $1', [id]); console.log('用户已删除');}
// 使用示例(async () => { await createTable(); const newUser = await addUser('Ivan', 'ivan@example.com'); console.log('已添加:', newUser);
const users = await getUsers(); console.log('所有用户:', users);
await updateUser(1, 'Petr'); await deleteUser(2);})();重要提示:始终使用参数化查询(通过 $1、$2),以避免 SQL 注入。
2. MongoDB:NoSQL 数据库
MongoDB 以类似 JSON 的文档格式 (BSON) 存储数据。对于 Node.js,使用官方驱动程序 mongodb 或流行的库 mongoose。在此示例中,我们将使用驱动程序。
2.1. 安装和连接
npm install mongodb连接到本地 MongoDB(默认端口 27017):
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017';const client = new MongoClient(uri);
async function connect() { await client.connect(); console.log('已连接到 MongoDB'); return client.db('mydb'); // 数据库 mydb}
module.exports = { connect, client };2.2. 对集合进行 CRUD 操作
在 MongoDB 中,表被称为集合,而行被称为