# 数据库集成

学习如何将应用连接到数据库。

# 支持的数据库

  • MongoDB
  • PostgreSQL
  • MySQL
  • SQLite
  • Redis

# MongoDB 示例

# 安装驱动

npm install mongodb
1

# 连接数据库

import { 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
}
1
2
3
4
5
6
7
8
9
10
11

# 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' })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 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)
1
2
3
4
5
6
7
8
9
10
11
Last Updated: 1/10/2026, 10:33:42 AM