Node.js 连接 MongoDB
要在 Node.js 中连接和操作 MongoDB,你需要使用官方的 MongoDB Node.js 驱动程序。以下是如何在 Node.js 中连接到 MongoDB 数据库的步骤。
1. 安装 MongoDB Node.js 驱动
首先,你需要通过 npm 安装 MongoDB 的 Node.js 驱动程序。打开终端并进入你的项目目录,然后运行以下命令:
npm install mongodb
该命令会安装官方的 MongoDB Node.js 驱动。
2. 连接到 MongoDB
安装完驱动程序后,你可以使用它来连接 MongoDB 数据库。以下是一个简单的连接示例:
const { MongoClient } = require('mongodb');
// MongoDB 连接字符串,假设 MongoDB 在本地运行
const url = 'mongodb://localhost:27017';
const dbName = 'test'; // 要连接的数据库名称
async function connectToMongoDB() {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
try {
// 连接到 MongoDB 服务器
await client.connect();
console.log('Connected to MongoDB');
// 选择数据库
const db = client.db(dbName);
// 使用数据库进行操作,例如选择集合
const collection = db.collection('users');
// 示例:查询所有文档
const users = await collection.find().toArray();
console.log(users);
} catch (err) {
console.error('MongoDB connection error:', err);
} finally {
// 确保连接在完成时关闭
await client.close();
}
}
connectToMongoDB();
代码说明:
- MongoClient:用于连接到 MongoDB 的客户端。
- useNewUrlParser 和 useUnifiedTopology:这两个选项是驱动程序的配置项,用于确保在连接时使用新的解析器和拓扑管理器。
- client.connect():异步连接到 MongoDB 数据库。
- db.collection(‘users’):选择名为
users的集合。 - find().toArray():查询集合中的所有文档并转换为数组。
3. 执行 CRUD 操作
插入数据
async function insertData() {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// 插入一条数据
const result = await collection.insertOne({ name: 'Alice', age: 25, city: 'New York' });
console.log(`New document inserted with _id: ${result.insertedId}`);
} catch (err) {
console.error('Insert operation failed:', err);
} finally {
await client.close();
}
}
insertData();
查询数据
async function findData() {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// 查询所有用户数据
const users = await collection.find({}).toArray();
console.log(users);
} catch (err) {
console.error('Find operation failed:', err);
} finally {
await client.close();
}
}
findData();
更新数据
async function updateData() {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// 更新 Alice 的年龄
const result = await collection.updateOne({ name: 'Alice' }, { $set: { age: 26 } });
console.log(`Matched ${result.matchedCount} document(s), modified ${result.modifiedCount} document(s)`);
} catch (err) {
console.error('Update operation failed:', err);
} finally {
await client.close();
}
}
updateData();
删除数据
async function deleteData() {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// 删除一个名为 Alice 的用户
const result = await collection.deleteOne({ name: 'Alice' });
console.log(`Deleted ${result.deletedCount} document(s)`);
} catch (err) {
console.error('Delete operation failed:', err);
} finally {
await client.close();
}
}
deleteData();
4. 处理错误和异常
在 Node.js 中处理 MongoDB 的错误和异常非常重要。你可以使用 try...catch 语句来捕获数据库操作中的异常,并进行相应处理。
例如,以下代码演示了如何捕获数据库连接错误:
async function connectToMongoDB() {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
console.log('Connected to MongoDB');
} catch (err) {
console.error('Failed to connect to MongoDB:', err.message);
} finally {
await client.close();
}
}
connectToMongoDB();
5. 使用 MongoDB 的聚合功能
MongoDB 提供了强大的聚合框架,允许你进行更复杂的数据查询、过滤、排序、分组等操作。
以下是一个使用聚合管道进行数据分组的示例:
async function aggregateData() {
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// 聚合查询,按城市分组并计算每个城市的用户数量
const pipeline = [
{ $group: { _id: '$city', count: { $sum: 1 } } }
];
const result = await collection.aggregate(pipeline).toArray();
console.log(result);
} catch (err) {
console.error('Aggregation failed:', err);
} finally {
await client.close();
}
}
aggregateData();
总结
- 使用 MongoDB Node.js 驱动连接到数据库,通过
MongoClient类和连接字符串。 - 通过
insertOne、find、updateOne和deleteOne等方法执行常见的 CRUD 操作。 - 使用
aggregate方法进行更复杂的聚合查询。 - 捕获和处理连接和查询中的异常,确保代码的鲁棒性。
通过这些步骤,你可以轻松在 Node.js 应用中实现与 MongoDB 的连接和数据操作。更多详细内容请关注其他相关文章。
MongoDB官方Node.js驱动程序的官方文档:MongoDB Node.js Driver Documentation