在JavaScript (Node.js)中操作数据库简介
\n现代Web开发几乎离不开与数据库的交互。无论是存储用户信息、博客文章还是分析数据——掌握数据库操作技能是每位开发者的必备能力。本文将介绍两种最流行的数据库类型:关系型数据库PostgreSQL和文档型数据库MongoDB。我们将用JavaScript (Node.js)编写简单示例,帮助您开始使用这两种系统。
\n\n1. 环境准备与依赖安装
\n在编写代码之前,需要安装用于Node.js与所选数据库交互的驱动程序。为此,请创建一个新项目并通过npm安装软件包。
\n\n安装驱动程序
\n- \n
- pg — 用于PostgreSQL的流行客户端。 \n
- mongoose — 用于MongoDB的ODM(对象文档映射器),可简化集合操作。 \n
mkdir db-example && cd db-example\nnpm init -y\nnpm install pg mongoose\n\n现在您的环境已准备好进行实验。
\n\n2. 从Node.js操作PostgreSQL
\nPostgreSQL是一种强大的关系型数据库,使用SQL进行查询。我们将连接到本地服务器,创建表并执行基本的CRUD(创建、读取、更新、删除)操作。
\n\n连接数据库
\n创建文件postgres.js并添加以下连接代码:
const { Pool } = require('pg');\n\nconst pool = new Pool({\n user: 'your_username',\n host: 'localhost',\n database: 'testdb',\n password: 'your_password',\n port: 5432,\n});\n\nasync function connect() {\n try {\n const client = await pool.connect();\n console.log('已连接到PostgreSQL');\n client.release();\n } catch (err) {\n console.error('连接错误:', err);\n }\n}\n\nconnect();\n\n创建表并插入数据
\n现在添加一个函数来创建users表并插入记录:
async function createTable() {\n const query = `\n CREATE TABLE IF NOT EXISTS users (\n id SERIAL PRIMARY KEY,\n name VARCHAR(100) NOT NULL,\n email VARCHAR(100) UNIQUE NOT NULL\n );\n `;\n await pool.query(query);\n console.log('users表已创建');\n}\n\nasync function insertUser(name, email) {\n const query = 'INSERT INTO users (name, email) VALUES ($1, $2) RETURNING *';\n const values = [name, email];\n const res = await pool.query(query, values);\n console.log('已添加用户:', res.rows[0]);\n}\n\n// 使用示例\ncreateTable().then(() => insertUser('伊万', 'ivan@example.com'));\n\n读取和更新数据
\n获取所有用户并更新邮箱:
\nasync function getUsers() {\n const res = await pool.query('SELECT * FROM users');\n console.log('所有用户:', res.rows);\n}\n\nasync function updateUserEmail(id, newEmail) {\n const query = 'UPDATE users SET email = $1 WHERE id = $2 RETURNING *';\n const res = await pool.query(query, [newEmail, id]);\n console.log('已更新用户:', res.rows[0]);\n}\n\ngetUsers().then(() => updateUserEmail(1, 'ivan_new@example.com'));\n\nPostgreSQL非常适合那些注重数据完整性和表之间复杂关系的项目。
\n\n3. 从Node.js操作MongoDB
\nMongoDB是一种NoSQL数据库,以类似JSON (BSON)的格式存储数据。它灵活且不需要严格的模式。我们将使用Mongoose进行操作。
\n\n连接MongoDB
\n创建文件mongo.js:
const mongoose = require('mongoose');\n\nconst connectDB = async