在Node.js應用程序中,導入MongoDB是一項常見任務。本文將詳細介紹如何在Node.js中連接和操作MongoDB數據庫,包括安裝必要的包、配置連接、執行基本的CRUD操作等步驟。
1. 安裝必要的包
首先,確保你已經安裝了Node.js和npm。然后,通過npm安裝MongoDB的Node.js驅動程序。
npm install mongodb
2. 連接到MongoDB
使用MongoDB驅動程序連接到MongoDB數據庫。以下是一個基本的連接示例:
const { MongoClient } = require('mongodb');const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });async function connect() {try {await client.connect();console.log('Connected to MongoDB');} catch (error) {console.error('Error connecting to MongoDB', error);}
}connect();
3. 選擇數據庫和集合
連接成功后,可以選擇數據庫和集合進行操作。以下是選擇數據庫和集合的示例:
async function connect() {try {await client.connect();console.log('Connected to MongoDB');const database = client.db('testdb');const collection = database.collection('testcollection');// 在這里進行CRUD操作} catch (error) {console.error('Error connecting to MongoDB', error);}
}connect();
?
4. CRUD操作
插入文檔
使用?insertOne
方法插入單個文檔,使用?insertMany
方法插入多個文檔。
async function insertDocument() {const database = client.db('testdb');const collection = database.collection('testcollection');const doc = { name: 'John Doe', age: 30, address: '123 Main St' };const result = await collection.insertOne(doc);console.log(`New document inserted with _id: ${result.insertedId}`);
}insertDocument();
?
查找文檔
使用?findOne
方法查找單個文檔,使用?find
方法查找多個文檔。
async function findDocuments() {const database = client.db('testdb');const collection = database.collection('testcollection');const query = { name: 'John Doe' };const document = await collection.findOne(query);console.log('Found document:', document);const cursor = collection.find({});const results = await cursor.toArray();console.log('Found documents:', results);
}findDocuments();
?
更新文檔
使用?updateOne
方法更新單個文檔,使用?updateMany
方法更新多個文檔。
async function updateDocument() {const database = client.db('testdb');const collection = database.collection('testcollection');const filter = { name: 'John Doe' };const updateDoc = { $set: { age: 31 } };const result = await collection.updateOne(filter, updateDoc);console.log(`Matched ${result.matchedCount} documents and modified ${result.modifiedCount} documents`);
}updateDocument();
?
刪除文檔
使用?deleteOne
方法刪除單個文檔,使用?deleteMany
方法刪除多個文檔。
async function deleteDocument() {const database = client.db('testdb');const collection = database.collection('testcollection');const query = { name: 'John Doe' };const result = await collection.deleteOne(query);console.log(`Deleted ${result.deletedCount} documents`);
}deleteDocument();