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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay