MongoDB與Node.js的集成主要通過使用MongoDB的官方Node.js驅動程序來實現。以下是一些關鍵步驟來幫助您開始集成:
npm install mongodb
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
console.log('Connected to MongoDB');
const db = client.db('your_database_name');
// 在這里執行數據庫操作
client.close();
});
例如,以下代碼演示了如何在Node.js應用程序中插入一個文檔:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
console.log('Connected to MongoDB');
const db = client.db('your_database_name');
const collection = db.collection('your_collection_name');
const newDocument = { key: 'value' };
collection.insertOne(newDocument, (err, res) => {
if (err) throw err;
console.log('Document inserted');
client.close();
});
});
這就是將MongoDB與Node.js集成的基本方法。您可以根據需要擴展此示例以執行更復雜的查詢和操作。