Mona Alfonso

Mona Alfonso

Web Developer and Educator with 5+ years of experience in tech.

1. Project Set Up

  • Create a new directory for your project and navigate to it in your terminal.
  • Run npm init -y to create a package.json file.
  • Install the required dependencies by running npm install express mongoose.

2. Create Server File

  • Create a new file called server.js (or any name you prefer).
  • Import the required modules at the top of the file:
const express = require('express');
const mongoose = require('mongoose');
const app = express();

3. Connect to MongoDB

  • Import the MongoDB connection URL (you can use a local or cloud-hosted MongoDB instance).
  • Connect to the MongoDB database using mongoose.connect():
const mongoURI = 'mongodb://localhost:27017/your [ ]database-name';
 
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.log(err));

4. Set Up Express Middleware

  • Configure Express to parse incoming JSON data:
app.use(express.json());

5. Define the MongoDB Schema and Model

  • Create a new file called models/yourModel.js (e.g., models/book.js).
  • Define the schema using mongoose.Schema and create a model using mongoose.model():
const mongoose = require('mongoose');
 
const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  published: Date
});
 
const Book = mongoose.model('Book', bookSchema);
 
module.exports = Book;

6. Create the CRUD Routes

  • In your server.js file, import the model you created:
const Book = require('./models/book');
  • Define the routes for CRUD operations:
// Create a new book
app.post('/books', async (req, res) => {
  const book = new Book(req.body);
  try {
    await book.save();
    res.status(201).send(book);
  } catch (err) {
    res.status(400).send(err);
  }
});
 
// Get all books
app.get('/books', async (req, res) => {
  try {
    const books = await Book.find();
    res.send(books);
  } catch (err) {
    res.status(500).send(err);
  }
});
 
// Get a specific book
app.get('/books/:id', async (req, res) => {
  try {
    const book = await Book.findById(req.params.id);
    if (!book) return res.status(404).send();
    res.send(book);
  } catch (err) {
    res.status(500).send(err);
  }
});
 
// Update a book
app.patch('/books/:id', async (req, res) => {
  try {
    const book = await Book.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!book) return res.status(404).send();
    res.send(book);
  } catch (err) {
    res.status(400).send(err);
  }
});
 
// Delete a book
app.delete('/books/:id', async (req, res) => {
  try {
    const book = await Book.findByIdAndDelete(req.params.id);
    if (!book) return res.status(404).send();
    res.send(book);
  } catch (err) {
    res.status(500).send(err);
  }
});

7. Start the Server

  • At the bottom of your server.js file, start the server:
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on port ${port}`));

8. Run the Application

  • In your terminal, run node server.js to start the server.
  • You can now use tools like Postman or cURL to interact with the CRUD routes (e.g., POST /books to create a new book, GET /books to get all books, etc.).

This tutorial covers the basic setup for a Node.js Express MongoDB Mongoose backend with CRUD functionality. You can extend this project by adding more features, such as authentication, validation, and error handling, as needed.

9. Seed Your MongoDB Book Collection (optional)

You can add an book entry to yoru database by using the POST request set up above, and then your Mongo database will have it's first record. However, if you want to start with some books already in your database, then you will need to seed your database with these initial records.

To seed your MongoDB database with some initial books, you can create a separate file (e.g., seed.js) and use the Mongoose models to insert data into the database. Here's how you can do it:

Create a seed.js file
  • In the root directory of your project, create a new file called seed.js.
Import the required modules and models
  • At the top of the seed.js file, import the required modules and the Mongoose model you created earlier:
const mongoose = require('mongoose');
const Book = require('./models/book');
 
const mongoURI = 'mongodb://localhost:27017/your-database-name';
Connect to MongoDB
  • Connect to the MongoDB database using mongoose.connect():
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.log(err));
Define the seed data
  • Create an array of book objects that you want to insert into the database:
const seedBooks = [
{
  title: 'Book 1',
  author: 'Author 1',
  published: new Date(2021, 0, 1) // January 1, 2021
},
{
  title: 'Book 2',
  author: 'Author 2',
  published: new Date(2022, 5, 15) // June 15, 2022
},
// Add more book objects as needed
];
Seed the database
  • Use the Book.insertMany() method to insert the seed data into the database:
const seedDB = async () => {
try {
  // Remove all existing books
  await Book.deleteMany({});
 
  // Insert seed books
  await Book.insertMany(seedBooks);
  console.log('Database seeded successfully');
} catch (err) {
  console.log(err);
} finally {
  mongoose.connection.close();
}
};
 
seedDB();