Introduction
In this guide, we'll walk you through the process of setting up a basic Node.js application that interacts with a MongoDB database. You'll learn how to connect to MongoDB, perform CRUD (Create, Read, Update, Delete) operations, and build a simple RESTful API. We'll provide code examples to help you get started.
Prerequisites
Before you begin, make sure you have the following prerequisites:
- Node.js installed on your system. You can download it from nodejs.org.
- MongoDB installed and running locally or accessible through a connection string.
- A code editor or integrated development environment (IDE) for writing and running Node.js applications.
Step 1: Setting Up Your Node.js Project
Start by creating a new directory for your Node.js project. Open your terminal and run the following commands:
mkdir my-node-mongodb-app
cd my-node-mongodb-app
npm init -y
This will create a new Node.js project with a
package.json
file. Step 2: Installing Dependencies
Next, install the required Node.js packages for MongoDB integration. Run the following command:
npm install mongodb express
This installs the
mongodb
driver for MongoDB and express
for building the API. Step 3: Creating a Connection to MongoDB
Now, you need to create a connection to your MongoDB database. In your Node.js application, create a file (e.g.,
app.js
) and add the following code: const express = require('express');
const { MongoClient } = require('mongodb');
const app = express();
const port = 3000;
const url = 'mongodb://localhost:27017'; // MongoDB connection URL
const dbName = 'mydb'; // Your database name
const client = new MongoClient(url, { useUnifiedTopology: true });
client.connect()
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 4: Building Your API
You can start building your API by defining routes and handling CRUD operations. Here's an example of creating a simple "GET" endpoint to retrieve data from MongoDB:
app.get('/data', (req, res) => {
const db = client.db(dbName);
const collection = db.collection('mycollection'); // Replace with your collection name
collection.find({}).toArray((err, result) => {
if (err) {
console.error('Error fetching data:', err);
res.status(500).send('Error fetching data');
} else {
res.json(result);
}
});
});
Step 5: Running Your Application
To run your Node.js application, use the following command:
node app.js
Your server will start, and you can access your API at
http://localhost:3000/data
. Conclusion
You've successfully set up a basic Node.js application with MongoDB integration. You can expand and enhance this application to perform more advanced CRUD operations, add authentication, and create a full-fledged API.