NodeJs MongoDB
Node.js MongoDB: A Guide to Using MongoDB with Node.js
MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format, making it ideal for applications that require a scalable and schema-less design. When combined with Node.js, developers can create powerful applications that leverage the strengths of both technologies.
Prerequisites
Ensure you have the following:
- Node.js: Installed from nodejs.org.
- MongoDB: Installed and running, or use a cloud service like MongoDB Atlas.
- MongoDB Driver for Node.js: Installed in your Node.js project.
Step 1: Set Up the Project
-
Create a project directory (if not already done):
bashmkdir node-mongodb cd node-mongodb
-
Initialize a Node.js project:
bashnpm init -y
-
Install the MongoDB driver:
bashnpm install mongodb
Step 2: Connect to MongoDB
-
Create a file named
app.js
:bashtouch app.js
-
Open
app.js
and add the following code to connect to the MongoDB server:javascriptconst { MongoClient } = require('mongodb'); // Replace the following with your MongoDB connection string const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); async function run() { try { // Connect to the MongoDB cluster await client.connect(); console.log('Connected to MongoDB'); // Perform operations here... } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { // Close the connection await client.close(); } } run().catch(console.error);
Step 3: Create a Database and Collection
To work with MongoDB, you need to create a database and a collection. Collections are similar to tables in relational databases.
-
Create a database and collection:
You can modify the
run
function to create a database and a collection:javascriptconst dbName = 'mydatabase'; const collectionName = 'users'; async function run() { try { await client.connect(); console.log('Connected to MongoDB'); const database = client.db(dbName); const collection = database.collection(collectionName); console.log(`Database: ${dbName}, Collection: ${collectionName}`); // Perform operations here... } catch (error) { console.error('Error connecting to MongoDB:', error); } finally { await client.close(); } }
Step 4: Insert Documents into the Collection
You can insert documents (similar to rows in SQL) into the MongoDB collection:
async function run() {
try {
await client.connect();
console.log('Connected to MongoDB');
const database = client.db(dbName);
const collection = database.collection(collectionName);
// Insert a single document
const user = { name: 'Alice', email: 'alice@example.com' };
const result = await collection.insertOne(user);
console.log(`Inserted document with _id: ${result.insertedId}`);
// Insert multiple documents
const users = [
{ name: 'Bob', email: 'bob@example.com' },
{ name: 'Charlie', email: 'charlie@example.com' }
];
const insertManyResult = await collection.insertMany(users);
console.log(`${insertManyResult.insertedCount} documents were inserted`);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
} finally {
await client.close();
}
}
Step 5: Retrieve Documents from the Collection
You can retrieve documents using the find
method:
async function run() {
try {
await client.connect();
console.log('Connected to MongoDB');
const database = client.db(dbName);
const collection = database.collection(collectionName);
// Find all documents
const allUsers = await collection.find().toArray();
console.log('All Users:', allUsers);
// Find a specific user
const user = await collection.findOne({ name: 'Alice' });
console.log('Found User:', user);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
} finally {
await client.close();
}
}
Step 6: Update Documents
You can update existing documents in the collection using the updateOne
or updateMany
methods:
async function run() {
try {
await client.connect();
console.log('Connected to MongoDB');
const database = client.db(dbName);
const collection = database.collection(collectionName);
// Update a specific user
const result = await collection.updateOne(
{ name: 'Alice' }, // Filter
{ $set: { email: 'alice.new@example.com' } } // Update
);
console.log(`${result.modifiedCount} document(s) were updated`);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
} finally {
await client.close();
}
}
Step 7: Delete Documents
You can delete documents using the deleteOne
or deleteMany
methods:
async function run() {
try {
await client.connect();
console.log('Connected to MongoDB');
const database = client.db(dbName);
const collection = database.collection(collectionName);
// Delete a specific user
const result = await collection.deleteOne({ name: 'Bob' });
console.log(`${result.deletedCount} document(s) were deleted`);
} catch (error) {
console.error('Error connecting to MongoDB:', error);
} finally {
await client.close();
}
}
Step 8: Run the Application
To run the Node.js script and perform CRUD operations, execute the following command in your terminal:
node app.js
You will see the results of the CRUD operations in the console.
Conclusion
In this guide, you’ve learned how to:
- Set up a Node.js project to connect to MongoDB.
- Perform basic CRUD operations: Create, Read, Update, and Delete documents in a MongoDB collection.
- Understand how to structure your Node.js application to interact with MongoDB effectively.
Web Technology View More
Learn Ansible
Ansible is an open-source automation tool that sim..
Learn HTML
HTML5 supports multimedia elements such as audio a..
Learn Angular 3
Angular..
Learn PHP
Introduction to PHP: A Powerful Scripting Language..
Learn Angular 2.0
Angular 2..
Learn Python
Python Tutorials..
Learn C# Sharp
C# Syntax - Learn the basic syntax of C# programmi..
Learn CSS
What is CSS?..
Learn Node Js
Node.js: A Powerful JavaScript Runtime for Server-..