Node.js is the most popular environment for MongoDB. The JavaScript syntax matches MongoDB's JSON documents perfectly. Integrating the two creates a massive productivity boost.
The official driver is distributed via NPM. You install it into your project folder easily. Run the command npm install mongodb.
The core class of the driver is MongoClient. It handles the connection and communication. It heavily utilizes modern JavaScript Promises and Async/Await.
To connect, you pass your connection string. You await the client.connect() execution. Once connected, you select your specific database.
Once the collection is targeted, you run standard commands. collection.insertOne() and collection.find() behave naturally. The API mirrors the MongoDB shell almost identically.
const { MongoClient } = require('mongodb');
async function run() {
const uri = "mongodb+srv://user:pass@cluster.net/";
const client = new MongoClient(uri);
try {
await client.connect();
const db = client.db("myApp");
const coll = db.collection("users");
// Find one document
const user = await coll.findOne({ name: "Akash" });
console.log(user);
} finally {
await client.close();
}
}
run();
Many Node.js developers use Mongoose instead. Mongoose is an Object Data Modeling library. It wraps the official driver to add strict schemas.
Always use try...catch blocks around database calls. This prevents your Node.js server from crashing unexpectedly. Network blips or duplicate key errors are easily caught.
The Node.js driver is robust and Promise-based. Use MongoClient to maintain a singular pool. Use Mongoose if you desire strict schema modeling.
Which core class is used to initialize the connection in the official Node.js driver?