In this tutorial, we'll walk through the process of creating a new project using Node.js, Express, and MongoDB, step by step.
Step 1: Set Up Your Project Directory
mkdir my_project
cd my_project
Step 2: Initialize Your Project
npm init -y
Step 3: Install Dependencies
npm install express mongoose
Step 4: Create Your Server File
touch server.js
Step 5: Write Your Server Code
Open server.js
in your preferred code editor and add the following code:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = process.env.PORT || 3000;
mongoose.connect('mongodb://localhost/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error connecting to MongoDB:', err);
process.exit(1);
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 6: Run Your Server
node server.js
Your server should now be running, and you can access it by navigating to http://localhost:3000
in your web browser.
Congratulations! You've successfully created a new project using Node.js, Express, and MongoDB.