Node.js 教程
Node.js 基础
Node.js 概述
Node.js 环境搭建
Node.js 基础语法
Node.js 模块
Node.js 异步编程
Node.js 核心模块
Node.js文件系统
Node.js路径模块(path)
Node.js的HTTP模块
Node.js的url模块
Node.js流模块(stream)
Node.js 常用工具与框架
npm 与包管理
Express 框架
数据库操作
Socket.io 与 WebSocket
Node.js 实战项目
Web 应用开发
API 开发
爬虫应用
自动化脚本
Node.js部署与优化
部署 Node.js 应用
Node.js性能优化
Node.js应用的安全性
Node.js 高级话题
Node.js中的设计模式
TypeScript 与 Node.js
GraphQL 与 API 开发
-
+
首页
数据库操作
### **1. MongoDB 基础与操作** MongoDB 是一种流行的 NoSQL 数据库,存储数据为 JSON 格式的文档。以下是在 Node.js 中使用 MongoDB 的示例: #### **连接 MongoDB** ```javascript const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); db.once('open', () => { console.log('Connected to MongoDB'); }); ``` #### **定义 Schema 和 Model** ```javascript const Schema = mongoose.Schema; const userSchema = new Schema({ name: String, email: String, age: Number }); const User = mongoose.model('User', userSchema); ``` #### **执行 CRUD 操作** - **创建(Create)** ```javascript const user = new User({ name: 'Alice', email: 'alice@example.com', age: 25 }); user.save() .then(() => console.log('User created')) .catch(err => console.error(err)); ``` - **读取(Read)** ```javascript User.find({ age: { $gt: 20 } }) .then(users => console.log(users)) .catch(err => console.error(err)); ``` - **更新(Update)** ```javascript User.findOneAndUpdate({ name: 'Alice' }, { age: 26 }, { new: true }) .then(updatedUser => console.log(updatedUser)) .catch(err => console.error(err)); ``` - **删除(Delete)** ```javascript User.findOneAndDelete({ name: 'Alice' }) .then(() => console.log('User deleted')) .catch(err => console.error(err)); ``` #### **高级操作** - **聚合查询** ```javascript User.aggregate([ { $match: { age: { $gt: 20 } } }, { $group: { _id: '$age', count: { $sum: 1 } } } ]) .then(result => console.log(result)) .catch(err => console.error(err)); ``` - **集合操作** ```javascript // 查询所有文档 User.find().exec() .then(users => console.log(users)) .catch(err => console.error(err)); ``` --- ### **2. MySQL 基础与操作** MySQL 是一种关系型数据库。以下是在 Node.js 中使用 MySQL 的示例: #### **连接 MySQL** ```javascript const mysql = require('mysql2/promise'); async function connect() { const connection = await mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'mydatabase' }); console.log('Connected to MySQL'); return connection; } ``` #### **执行 CRUD 操作** - **创建(Create)** ```javascript async function createUser(connection) { await connection.execute( 'INSERT INTO users (name, email, age) VALUES (?, ?, ?)', ['Bob', 'bob@example.com', 30] ); } ``` - **读取(Read)** ```javascript async function getUsers(connection) { const [rows] = await connection.execute('SELECT * FROM users'); console.log(rows); } ``` - **更新(Update)** ```javascript async function updateUser(connection) { await connection.execute( 'UPDATE users SET age = ? WHERE name = ?', [31, 'Bob'] ); } ``` - **删除(Delete)** ```javascript async function deleteUser(connection) { await connection.execute('DELETE FROM users WHERE name = ?', ['Bob']); } ``` #### **事务处理** ```javascript async function transaction(connection) { await connection.beginTransaction(); try { await connection.execute( 'UPDATE accounts SET balance = balance - ? WHERE user_id = ?', [100, 1] ); await connection.execute( 'UPDATE accounts SET balance = balance + ? WHERE user_id = ?', [100, 2] ); await connection.commit(); } catch (err) { await connection.rollback(); throw err; } } ``` #### **查询优化** - **添加索引** ```javascript await connection.execute('CREATE INDEX idx_age ON users(age)'); ``` --- ### **3. Redis 基础与操作** Redis 是一种内存数据库,常用于缓存、会话存储等。以下是在 Node.js 中使用 Redis 的示例: #### **连接 Redis** ```javascript const redis = require('redis'); const client = redis.createClient({ url: 'redis://localhost:6379' }); client.on('error', err => { console.error('Redis error:', err); }); client.on('connect', () => { console.log('Connected to Redis'); }); ``` #### **执行基本操作** - **字符串操作** ```javascript // 设置键值对 client.set('key', 'value', (err, reply) => { if (err) throw err; console.log(reply); // 输出: OK }); // 获取键值 client.get('key', (err, reply) => { if (err) throw err; console.log(reply); // 输出: value }); ``` - **哈希操作** ```javascript // 设置哈希字段 client.hset('user:1', 'name', 'Alice', (err, reply) => { if (err) throw err; console.log(reply); // 输出: 1 }); // 获取哈希字段 client.hget('user:1', 'name', (err, reply) => { if (err) throw err; console.log(reply); // 输出: Alice }); ``` - **列表操作** ```javascript // 添加列表元素 client.lpush('messages', 'Hello', (err, reply) => { if (err) throw err; console.log(reply); // 输出: 1 }); // 获取列表元素 client.lrange('messages', 0, -1, (err, reply) => { if (err) throw err; console.log(reply); // 输出: ['Hello'] }); ``` #### **高级操作** - **事务处理** ```javascript client.multi() .incr('counter') .incr('another_counter') .exec((err, replies) => { if (err) throw err; console.log(replies); // 输出: [ 1, 1 ] }); ``` - **主从复制配置** 统一使用异步的方式操作 Redis,确保数据一致性,或者通过 Redis 的主从复制机制进行配置。 通过以上代码示例,你可以在 Node.js 中操作 MongoDB、MySQL 和 Redis 数据库,实现基本的 CRUD 操作以及一些高级功能。
wwbang
2025年2月26日 18:38
转发文档
收藏文档
上一篇
下一篇
手机扫码
复制链接
手机扫一扫转发分享
复制链接
Markdown文件
分享
链接
类型
密码
更新密码