DEV Community

Cover image for Database Integration
Suhas Palani
Suhas Palani

Posted on

Database Integration

  • Topic: "Working with Databases: MongoDB and Mongoose"
  • Description: Introduction to MongoDB and Mongoose for database integration in Node.js applications.

Content:

1. Introduction to MongoDB

  • What is MongoDB: Explain MongoDB as a NoSQL database.
  • Why MongoDB: Discuss the benefits like flexibility, scalability, and performance.

2. Setting Up MongoDB

  • Installation: Provide links and instructions for installing MongoDB locally or using a service like MongoDB Atlas.
  • Connecting to MongoDB:

    const mongoose = require('mongoose');
    
    mongoose.connect('mongodb://localhost:27017/mydatabase', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    }).then(() => {
      console.log('Connected to MongoDB');
    }).catch(err => {
      console.error('Connection error', err);
    });
    

3. Defining a Schema with Mongoose

  • Install Mongoose:

    npm install mongoose
    
  • Define a Book Schema:

    const bookSchema = new mongoose.Schema({
      title: String,
      author: String,
      publishedDate: Date,
      pages: Number
    });
    
    const Book = mongoose.model('Book', bookSchema);
    

4. CRUD Operations with Mongoose

  • Create Operation:

    app.post('/books', async (req, res) => {
      const book = new Book(req.body);
      try {
        await book.save();
        res.status(201).json(book);
      } catch (err) {
        res.status(400).json({ error: err.message });
      }
    });
    
  • Read Operations:

    app.get('/books', async (req, res) => {
      try {
        const books = await Book.find();
        res.json(books);
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    });
    
    app.get('/books/:id', async (req, res) => {
      try {
        const book = await Book.findById(req.params.id);
        if (book) {
          res.json(book);
        } else {
          res.status(404).send('Book not found');
        }
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    });
    
  • Update Operation:

    app.put('/books/:id', async (req, res) => {
      try {
        const book = await Book.findByIdAndUpdate(req.params.id, req.body, { new: true });
        if (book) {
          res.json(book);
        } else {
          res.status(404).send('Book not found');
        }
      } catch (err) {
        res.status(400).json({ error: err.message });
      }
    });
    
  • Delete Operation:

    app.delete('/books/:id', async (req, res) => {
      try {
        const book = await Book.findByIdAndDelete(req.params.id);
        if (book) {
          res.status(204).send();
        } else {
          res.status(404).send('Book not found');
        }
      } catch (err) {
        res.status(500).json({ error: err.message });
      }
    });
    

5. Testing with Postman

  • Repeat Testing: Demonstrate testing the CRUD operations with Postman or Curl.

Top comments (0)