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.

Image of AssemblyAI tool

Challenge Submission: SpeechCraft - AI-Powered Speech Analysis for Better Communication

SpeechCraft is an advanced real-time speech analytics platform that transforms spoken words into actionable insights. Using cutting-edge AI technology from AssemblyAI, it provides instant transcription while analyzing multiple dimensions of speech performance.

Read full post

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay