a detailed step-by-step guide for setting up a Node.js server using Express and MongoDB Atlas:
Key Note | |||
---|---|---|---|
Emoji | Description | Emoji | Description |
π΄ | Main Topic | π | Regular Note |
πΏ | Paragraph | π | High Value info |
π | Heavy Note | 𧨠| Careful this |
π | Attention Note | β | Stop! check the point |
π·οΈ | Regular Note | π― | Focus |
Expand Table of Contents
- πΏ 1. Initialize Your Project
- πΏ 2. Install Dependencies
- πΏ 3. Create an index.js File
- πΏ 4. Initialize Express
- πΏ 5. Enable CORS Middleware
- πΏ 6. Use JSON Middleware
- πΏ 7. Set the Port
- πΏ 8. Create a Basic Route
- πΏ 9. Start the Server
- πΏ Final Output π΄ MongoDB Atlas Setup
- πΏ 1.Create a MongoDB Atlas Account
- πΏ 2. Set Up a Cluster
- πΏ 3. Create Database User and Name the Database
- πΏ 4. Environment Configuration
- πΏ 5. Store Database Credentials in the Environment File
npm init -y
npm i express cors dotenv mongodb
Initialize your main server file.
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors());
app.use(express.json());
Define the port in the environment variable or default to 5000.
const port = process.env.PORT || 5000;
Create a simple route to check if the server is running.
app.get('/', (req, res) => {
res.send('Server is running');
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
const express = require ('express')
const app = express();
const cors = require('cors');
const port = process.env.PORT || 5000;
// middleware
app.use(cors());
app.use(express.json());
app.get('/', (req, res) => {
res.send('server is running')
})
app.listen(port, () => {
console.log( `Server is running on port ${port}`)
})
=> Sign up for MongoDB Atlas and log in.
=> Create a new cluster and configure it.
=> Create a database user with privileges and name your database.
=> Create a .env file and add it to .gitignore.
DB_USER=yourDatabaseUser
DB_PASS=yourDatabasePassword
Go to "Database Access" and copy the connection string provided by MongoDB Atlas.
Replace the MongoDB URI in your code with environment variables.
Inside your server code, establish a connection to MongoDB using the MongoClient.
const { MongoClient } = require('mongodb');
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
if (err) {
console.error('Error connecting to MongoDB:', err);
return;
}
const menuCollection = client.db('bistroDb').collection('menu');
const reviewCollection = client.db('bistroDb').collection('reviews');
app.get('/menu', async (req, res) => {
const result = await menuCollection.find().toArray();
res.send(result);
});
});
It's important to manage connections properly. Ensure you close the client when your server stops:
process.on('SIGINT', () => {
client.close();
process.exit();
});
const express = require ('express')
const app = express();
const cors = require('cors');
require('dotenv').config()
const port = process.env.PORT || 5000;
// middleware
app.use(cors());
app.use(express.json());
const { MongoClient, ServerApiVersion } = require('mongodb');
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.d94f49k.mongodb.net/?retryWrites=true&w=majority`;
// Create a MongoClient with a MongoClientOptions object to set the Stable API version
const client = new MongoClient(uri, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
const menuCollection = client.db("redCafe").collection("menu");
const reviewCollection = client.db("redCafe").collection("reviews");
app.get('/menu', async(req, res) =>{
const result = await menuCollection.find().toArray();
res.send(result);
})
// Send a ping to confirm a successful connection
await client.db("admin").command({ ping: 1 });
console.log("Pinged your deployment. You successfully connected to MongoDB!");
} finally {
// Ensures that the client will close when you finish/error
// await client.close();
}
}
run().catch(console.dir);
app.get('/', (req, res) => {
res.send('server is running')
})
app.listen(port, () => {
console.log( `Server is running on port ${port}`)
})
Note: This hand note walks you through setting up a basic Node.js server using Express and connecting it to MongoDB Atlas. Remember to replace placeholder values with your actual credentials and adapt the code as needed for your project.
Here's an example of how CRUD operations can be implemented:
app.post('/menu', async (req, res) => {
try {
const newItem = req.body;
const result = await menuCollection.insertOne(newItem);
res.json(result.ops[0]);
} catch (err) {
console.error('Error creating item:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
app.post('/carts', async (req, res) => {
const item = req.body;
console.log(item);
const result = await cartCollection.insertOne(item);
res.send(result);
})
app.get('/menu', async (req, res) => {
try {
const result = await menuCollection.find().toArray();
res.json(result);
} catch (err) {
console.error('Error fetching menu:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
**Another example:**
app.get('/reviews', async(req, res) =>{
const result = await reviewCollection.find().toArray();
res.send(result);
})
app.put('/menu/:id', async (req, res) => {
try {
const itemId = req.params.id;
const updatedItem = req.body;
const result = await menuCollection.updateOne({ _id: itemId }, { $set: updatedItem });
res.json(result);
} catch (err) {
console.error('Error updating item:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
The PATCH method in HTTP is used to apply partial modifications to a resource. It's commonly used to update specific fields of an existing resource without requiring the client to send the entire representation of that resource.
In the context of a RESTful API, the PATCH method is often used when you want to update specific attributes or properties of an existing resource identified by a unique identifier (like an ID).
app.patch('/users/admin/:id', async (req, res) => {
const id = req.params.id;
console.log(id);
const filter = { _id: new ObjectId(id) };
const updateDoc = {
$set: {
role: 'admin'
},
};
const result = await usersCollection.updateOne(filter, updateDoc);
res.send(result);
})
app.delete('/menu/:id', async (req, res) => {
try {
const itemId = req.params.id;
const result = await menuCollection.deleteOne({ _id: itemId });
res.json(result);
} catch (err) {
console.error('Error deleting item:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
app.delete('/carts/:id', async (req, res) => {
const id = req.params.id;
const query = { _id: new ObjectId(id) };
const result = await cartCollection.deleteOne(query);
res.send(result);
})
Demonstrates aggregating data, such as calculating the total sum of prices for all items in the menu.
app.get('/menu/pricesummary', async (req, res) => {
try {
const pipeline = [
{
$group: {
_id: null,
total: { $sum: '$price' }
}
}
];
const result = await menuCollection.aggregate(pipeline).toArray();
res.json(result);
} catch (err) {
console.error('Error aggregating prices:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
Shows how to filter documents based on criteria (here, filtering by a specific category) and sort the results.
app.get('/menu/sorted', async (req, res) => {
try {
const filter = { category: 'Coffee' }; // Example filter
const sortCriteria = { price: -1 }; // Sort by price descending
const result = await menuCollection.find(filter).sort(sortCriteria).toArray();
res.json(result);
} catch (err) {
console.error('Error filtering and sorting menu:', err);
res.status(500).json({ error: 'Internal server error' });
}
});
Illustrates how to project specific fields in the result and exclude others using projection in MongoDB.
app.get('/menu/projected', async (req, res) => {
try {
const projection = { name: 1, price: 1, _id: 0 }; // Only retrieve name and price, exclude _id
const result = await menuCollection.find().project(projection).toArray();
res.json(result);
} catch (err) {
console.error('Error projecting menu:', err);
res.status(500).json({ error: 'Internal server error' });
}
});