app-generator / docs

App Generator - The Official Documentation | AppSeed
https://docs.appseed.us
1 stars 1 forks source link

Working with Databases in nodejs #125

Open mahfujul-helios opened 1 month ago

mahfujul-helios commented 1 month ago

Working with Databases in nodejs

A Comprehensive Guide to Database Integration in Node.js

Introduction to databases and database systems:

Databases are organized collections of data that store and manage information efficiently. They provide a structured way to store and retrieve data, ensuring data integrity and security. Databases play a vital role in various applications, enabling easy access, manipulation, and analysis of data.

Key Concepts:

A database system is a software application that allows users to store, manage, and retrieve data effectively. It provides a structured environment to organize data, enabling efficient access and manipulation. A database system consists of a database management system (DBMS), which is the core software responsible for handling database operations, and the database itself, which is the collection of structured data.

Key Concepts of Database Systems:

Connect to database using mongoose

Install Mongoose: Start by installing the Mongoose package from npm. Open your terminal and run the following command:

npm install mongoose

  1. Import Mongoose: In your Node.js application, import the Mongoose module using the require statement:

const mongoose = require('mongoose');

mongoose.connect('<db_url>', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to the database');
  })
  .catch((error) => {
    console.error('Error connecting to the database:', error);
  });

Ensure you replace with the actual URL of your MongoDB database. The { useNewUrlParser: true, useUnifiedTopology: true } options are recommended to ensure proper connection and compatibility.

The error event is triggered if there is an error during the connection, and the open event is triggered when the connection is successfully established.

CRUD operations with MongoDB:

Define a Schema: Start by defining a schema that represents the structure of your MongoDB documents. A schema defines the fields, types, and validation rules for the data. Here’s an example of a simple user schema:

const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  name: {
    require: true,
    type: String,
  },
  email: {
    require: true,
    type: String,
  },
  age: {
    require: true,
    type: Number,
  },
});
const model = mongoose.model("User", userSchema);

Create a Document: To create a new document, instantiate a model based on the schema and save it to the database. Here’s an example:

async function createUser(req, res) {
  const data = new Model({
    name: req.body.name,
    age: req.body.age,
    email: req.body.email,
  });
  try {
    const dataToSave = await data.save();
    res
      .status(200)
      .json(
        new BaseResponse().createSuccessResponse(
          200,
          dataToSave,
          "user created"
        )
      );
    // res.status(200).json(dataToSave);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
}

Read Documents: To retrieve documents from the database, you can use methods like find(), findOne(), or query helpers provided by Mongoose. Here's an example using find():

async function getUser(req, res) {
  try {
    const data = await Model.find({ _id: req.params.id });
    res.json(data);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
}

Update a Document: To update a document, you can use methods like updateOne(), updateMany(), or findOneAndUpdate(). Here's an example using findOneAndUpdate():

async function updateUser(req, res) {
  try {
    const data = await Model.findOneAndUpdate(
      { _id: req.params.id }, // Condition to find the document to update
      { ...req.body }, // New values to update
      { new: true } // Set to true to return the modified document as the result
    res.json(data);

  } catch (error) {
    res.status(500).json({ message: error.message });
  }
}

Delete a Document: To delete a document, you can use methods like deleteOne() or deleteMany(). Here's an example using deleteOne():


async function deleteUser(req, res) {
  try {
    const id = req.params.id;
    const data = await Model.findByIdAndDelete(id);
    res.send(`Document with ${data.name} has been deleted..`);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
}
**```
Database Queries and Indexing:**
Efficient database operations are crucial for modern applications. To optimize performance, harnessing the power of database queries and indexing is essential. In this article, we explore key strategies for leveraging queries and indexing to enhance the speed and efficiency of your database operations.

Queries: Unveiling the Right Data

- Filter data using query operators ($eq, $ne, $gt, $lt, $in).
- Project only necessary fields to reduce data transfer.
- Sort query results for desired ordering.
- Implement limit and skip for pagination and result set control.
- Indexing: Accelerating Data Access

- Create single-field indexes for frequently queried fields.
- Utilize compound indexes for queries involving multiple fields.
- Employ unique indexes for fields with unique values.
- Optimize and maintain indexes to ensure ongoing performance.