Project 3: Full-Stack Note-Taking Application
3. Building the Backend
The backend of our note-taking application will handle CRUD operations for notes, manage user authentication (optional), and interact with the MongoDB database to store and retrieve data. This section will guide you through setting up the Express server, defining the database schema with Mongoose, and implementing API routes.
3.1 Server Initialization
- Create the Main Server File:
- In your
server
directory, create a file namedserver.js
. - This file will be the entry point for your server.
- In your
- Basic Server Setup:
- Set up an Express server with initial configurations:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config(); // Load environment variables from .env file
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json()); // Middleware to parse JSON
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
3.2 Database Connection
- Configure MongoDB with Mongoose:
- Ensure you have the MongoDB connection URI in your
.env
file (e.g., from MongoDB Atlas or your local MongoDB setup). - Connect to MongoDB using Mongoose:
const dbURI = process.env.MONGODB_URI;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Database connected successfully'))
.catch(err => console.error('MongoDB connection error:', err));
- Ensure you have the MongoDB connection URI in your
3.3 Models
- Define a Mongoose Schema for Notes:
- In the
server/models
directory, create a file namedNote.js
. - Define the schema and model for a note:
const mongoose = require('mongoose');
const noteSchema = new mongoose.Schema({
title: {
type: String,
required: true,
trim: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const Note = mongoose.model('Note', noteSchema);
module.exports = Note;
- In the
3.4 API Routes
- Set Up Express Routes for CRUD Operations:
- Create a
routes
directory and a file for notes routes (notes.js
):const express = require('express');
const router = express.Router();
const Note = require('../models/Note');
// GET all notes
router.get('/', async (req, res) => {
try {
const notes = await Note.find();
res.json(notes);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// POST a new note
router.post('/', async (req, res) => {
const note = new Note({
title: req.body.title,
content: req.body.content
});
try {
const newNote = await note.save();
res.status(201).json(newNote);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Additional routes for PUT and DELETE
module.exports = router;
- Integrate Routes into the Server:
- In
server.js
, import and use the routes:const notesRouter = require('./routes/notes');
app.use('/api/notes', notesRouter);
With the backend setup complete, your server is now capable of handling requests to manage notes, including creating, reading, updating, and deleting them. This robust backend architecture ensures that your application can efficiently process and store data, serving as the backbone for the note-taking functionality.
3. Building the Backend
The backend of our note-taking application will handle CRUD operations for notes, manage user authentication (optional), and interact with the MongoDB database to store and retrieve data. This section will guide you through setting up the Express server, defining the database schema with Mongoose, and implementing API routes.
3.1 Server Initialization
- Create the Main Server File:
- In your
server
directory, create a file namedserver.js
. - This file will be the entry point for your server.
- In your
- Basic Server Setup:
- Set up an Express server with initial configurations:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config(); // Load environment variables from .env file
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json()); // Middleware to parse JSON
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
3.2 Database Connection
- Configure MongoDB with Mongoose:
- Ensure you have the MongoDB connection URI in your
.env
file (e.g., from MongoDB Atlas or your local MongoDB setup). - Connect to MongoDB using Mongoose:
const dbURI = process.env.MONGODB_URI;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Database connected successfully'))
.catch(err => console.error('MongoDB connection error:', err));
- Ensure you have the MongoDB connection URI in your
3.3 Models
- Define a Mongoose Schema for Notes:
- In the
server/models
directory, create a file namedNote.js
. - Define the schema and model for a note:
const mongoose = require('mongoose');
const noteSchema = new mongoose.Schema({
title: {
type: String,
required: true,
trim: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const Note = mongoose.model('Note', noteSchema);
module.exports = Note;
- In the
3.4 API Routes
- Set Up Express Routes for CRUD Operations:
- Create a
routes
directory and a file for notes routes (notes.js
):const express = require('express');
const router = express.Router();
const Note = require('../models/Note');
// GET all notes
router.get('/', async (req, res) => {
try {
const notes = await Note.find();
res.json(notes);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// POST a new note
router.post('/', async (req, res) => {
const note = new Note({
title: req.body.title,
content: req.body.content
});
try {
const newNote = await note.save();
res.status(201).json(newNote);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Additional routes for PUT and DELETE
module.exports = router;
- Integrate Routes into the Server:
- In
server.js
, import and use the routes:const notesRouter = require('./routes/notes');
app.use('/api/notes', notesRouter);
With the backend setup complete, your server is now capable of handling requests to manage notes, including creating, reading, updating, and deleting them. This robust backend architecture ensures that your application can efficiently process and store data, serving as the backbone for the note-taking functionality.
3. Building the Backend
The backend of our note-taking application will handle CRUD operations for notes, manage user authentication (optional), and interact with the MongoDB database to store and retrieve data. This section will guide you through setting up the Express server, defining the database schema with Mongoose, and implementing API routes.
3.1 Server Initialization
- Create the Main Server File:
- In your
server
directory, create a file namedserver.js
. - This file will be the entry point for your server.
- In your
- Basic Server Setup:
- Set up an Express server with initial configurations:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config(); // Load environment variables from .env file
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json()); // Middleware to parse JSON
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
3.2 Database Connection
- Configure MongoDB with Mongoose:
- Ensure you have the MongoDB connection URI in your
.env
file (e.g., from MongoDB Atlas or your local MongoDB setup). - Connect to MongoDB using Mongoose:
const dbURI = process.env.MONGODB_URI;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Database connected successfully'))
.catch(err => console.error('MongoDB connection error:', err));
- Ensure you have the MongoDB connection URI in your
3.3 Models
- Define a Mongoose Schema for Notes:
- In the
server/models
directory, create a file namedNote.js
. - Define the schema and model for a note:
const mongoose = require('mongoose');
const noteSchema = new mongoose.Schema({
title: {
type: String,
required: true,
trim: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const Note = mongoose.model('Note', noteSchema);
module.exports = Note;
- In the
3.4 API Routes
- Set Up Express Routes for CRUD Operations:
- Create a
routes
directory and a file for notes routes (notes.js
):const express = require('express');
const router = express.Router();
const Note = require('../models/Note');
// GET all notes
router.get('/', async (req, res) => {
try {
const notes = await Note.find();
res.json(notes);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// POST a new note
router.post('/', async (req, res) => {
const note = new Note({
title: req.body.title,
content: req.body.content
});
try {
const newNote = await note.save();
res.status(201).json(newNote);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Additional routes for PUT and DELETE
module.exports = router;
- Integrate Routes into the Server:
- In
server.js
, import and use the routes:const notesRouter = require('./routes/notes');
app.use('/api/notes', notesRouter);
With the backend setup complete, your server is now capable of handling requests to manage notes, including creating, reading, updating, and deleting them. This robust backend architecture ensures that your application can efficiently process and store data, serving as the backbone for the note-taking functionality.
3. Building the Backend
The backend of our note-taking application will handle CRUD operations for notes, manage user authentication (optional), and interact with the MongoDB database to store and retrieve data. This section will guide you through setting up the Express server, defining the database schema with Mongoose, and implementing API routes.
3.1 Server Initialization
- Create the Main Server File:
- In your
server
directory, create a file namedserver.js
. - This file will be the entry point for your server.
- In your
- Basic Server Setup:
- Set up an Express server with initial configurations:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const dotenv = require('dotenv');
dotenv.config(); // Load environment variables from .env file
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json()); // Middleware to parse JSON
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
3.2 Database Connection
- Configure MongoDB with Mongoose:
- Ensure you have the MongoDB connection URI in your
.env
file (e.g., from MongoDB Atlas or your local MongoDB setup). - Connect to MongoDB using Mongoose:
const dbURI = process.env.MONGODB_URI;
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Database connected successfully'))
.catch(err => console.error('MongoDB connection error:', err));
- Ensure you have the MongoDB connection URI in your
3.3 Models
- Define a Mongoose Schema for Notes:
- In the
server/models
directory, create a file namedNote.js
. - Define the schema and model for a note:
const mongoose = require('mongoose');
const noteSchema = new mongoose.Schema({
title: {
type: String,
required: true,
trim: true
},
content: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const Note = mongoose.model('Note', noteSchema);
module.exports = Note;
- In the
3.4 API Routes
- Set Up Express Routes for CRUD Operations:
- Create a
routes
directory and a file for notes routes (notes.js
):const express = require('express');
const router = express.Router();
const Note = require('../models/Note');
// GET all notes
router.get('/', async (req, res) => {
try {
const notes = await Note.find();
res.json(notes);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
// POST a new note
router.post('/', async (req, res) => {
const note = new Note({
title: req.body.title,
content: req.body.content
});
try {
const newNote = await note.save();
res.status(201).json(newNote);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
// Additional routes for PUT and DELETE
module.exports = router;
- Integrate Routes into the Server:
- In
server.js
, import and use the routes:const notesRouter = require('./routes/notes');
app.use('/api/notes', notesRouter);
With the backend setup complete, your server is now capable of handling requests to manage notes, including creating, reading, updating, and deleting them. This robust backend architecture ensures that your application can efficiently process and store data, serving as the backbone for the note-taking functionality.