Sure! I'll walk you through the steps to create an Express application using MongoDB and Node.js with an example. We'll create a simple "Todo List" application that allows users to manage their tasks.
Set up the project:
Create a new directory for your project.
Open a terminal and navigate to the project directory.
Run the following command to initialize a new Node.js project:
npm init -y
Install the necessary dependencies:
npm install express mongoose
Create the Express server:
Create a new file named server.js.
Import the necessary modules and set up the Express app.
Define the basic server configuration:
// server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const PORT = 3000;
// Connect to MongoDB
mongoose.connect('mongodb://localhost/todo-app', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
// Middleware
app.use(express.json());
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Define the MongoDB model:
Create a new directory named models.
Inside the models directory, create a new file named Todo.js.
Define the Todo schema and export the model:
// models/Todo.js
const mongoose = require('mongoose');
const todoSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
completed: {
type: Boolean,
default: false,
},
});
const Todo = mongoose.model('Todo', todoSchema);
module.exports = Todo;
Create the API routes and controllers:
Create a new directory named routes.
Inside the routes directory, create a new file named todos.js.
Define the routes for managing todos and implement the controller logic:
// routes/todos.js
const express = require('express');
const router = express.Router();
const Todo = require('../models/Todo');
// Get all todos
router.get('/', async (req, res) => {
try {
const todos = await Todo.find();
res.json(todos);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Create a new todo
router.post('/', async (req, res) => {
try {
const { title } = req.body;
const todo = new Todo({
title,
});
await todo.save();
res.status(201).json(todo);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Update a todo
router.put('/:id', async (req, res) => {
try {
const { id } = req.params;
const { title, completed } = req.body;
const todo = await Todo.findByIdAndUpdate(
id,
{ title, completed },
{ new: true }
);
res.json(todo);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// Delete a todo
router.delete('/:id', async (req, res) => {
try {
const { id } = req.params;
await Todo.findByIdAndDelete(id);
res.sendStatus(204
Another Way
Top comments (0)