Database Integration
学习如何将应用连接到数据库。
支持的数据库
Section titled “支持的数据库”- MongoDB
- PostgreSQL
- MySQL
- SQLite
- Redis
MongoDB 示例
Section titled “MongoDB 示例”npm install mongodbimport { MongoClient } from 'mongodb'
const client = new MongoClient('mongodb://localhost:27017')
async function connect() { await client.connect() console.log('Connected to MongoDB')
const db = client.db('myapp') return db}CRUD 操作
Section titled “CRUD 操作”// 创建await db.collection('users').insertOne({ name: 'Alice', email: 'alice@example.com'})
// 读取const user = await db.collection('users').findOne({ name: 'Alice' })
// 更新await db.collection('users').updateOne( { name: 'Alice' }, { $set: { age: 25 } })
// 删除await db.collection('users').deleteOne({ name: 'Alice' })PostgreSQL 示例
Section titled “PostgreSQL 示例”import pg from 'pg'
const pool = new pg.Pool({ host: 'localhost', database: 'myapp', user: 'postgres', password: 'password'})
const result = await pool.query('SELECT * FROM users')console.log(result.rows)