mongoDB

mongoDB

·

4 min read

MongoDB is a source-available, cross-platform, document-oriented database program. Classified as a NoSQL database product, MongoDB utilizes JSON-like documents with optional schemas.

Types of Databases

What is Mongoose ?

  1. Object Data Modeling (ODM):

    • Mongoose is an ODM library for MongoDB, helping you model data in a structured way.
  2. Schema and Model:

    • It allows you to define schemas to structure your data and create models based on those schemas for interacting with MongoDB.
  3. Simplified Interaction:

    • Mongoose simplifies CRUD operations (Create, Read, Update, Delete) on MongoDB documents, providing methods for easy data manipulation.
  4. Validation and Middleware:

    • You can enforce data validation rules and add custom logic with middleware functions.
  5. Connection to MongoDB:

    • Easily connect to MongoDB databases using Mongoose, specifying connection details like URI and options.

Let's say we have to connect our application to the mongodb

const mongoose = require("mongoose"); // Import the mongoose from npm

Let's connect it when the mongodb atlas setup is completed and we have the final URL(Uniform Resource Locator)

mongoose
  .connect(
    "mongodb+srv://<username>:<password>@cluster0.ertdtcy.mongodb.net..."
  )
  .then(() => console.log("Connection successful..."))
  .catch((err) => console.error("Connection failed:", err));

Handling the Promises since Mongoose supports async function

Let's Make us a Schema(The way we want out datas to be represented in the mongodb)

// Schema definition
const playlistSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  ctype: String,
  videos: Number,
  author: String,
  active: Boolean,
  date: {
    type: Date,
    default: Date.now,
  },
});

// Model creation
const Playlist = mongoose.model("Playlist", playlistSchema);

Now lets create out data which needs to be pushed on

// Document creation and insertion

const reactPlaylist = new Playlist({
  name: "React JS",
  ctype: "Frontend",
  videos: 80,
  author: "Thiru",
  active: true
});

reactPlaylist
  .save()
  .then(() => console.log("Document saved successfully..."))
  .catch((err) => console.error("Failed to save document:", err));

Our Output will be such in terminal

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Connection successful...
Document saved successfully...
Document saved successfully...

Another Way to create the models Lets make a function wrapper

// Function to create and save a document
const createDocument = async () => {
    try {
      const expressPlaylist = new Playlist({
        name: "Express",
        ctype: "Backend",
        videos: 100,
        author: "Thiru",
        active: true,
      });

      await expressPlaylist.save(); // Wait for the document to be saved
      console.log("Document saved successfully...");
    } catch (err) {
      console.error("Failed to save document:", err);
    }
  };

  // Call the function to create and save the document
  createDocument();

What are ORMs?

  1. Definition:

    • ORMs bridge the gap between object-oriented programming languages and relational databases.

    • They enable developers to interact with databases using object-oriented paradigms rather than direct SQL queries.

  2. Functionality:

    • ORMs convert data between object-oriented models and relational database tables.

    • They abstract away the complexities of SQL queries, providing a higher-level interface for database operations.

  3. Benefits:

    • Improve productivity by simplifying database interactions.

    • Enhance portability by allowing switching between different database systems with minimal code changes.

    • Increase maintainability by providing a cleaner, object-oriented approach to database access.

    • Enhance security by offering built-in protection against common vulnerabilities like SQL injection.

Mongoose is ODM - Object Document Mapping

We Majorly use PRISMA for javascript related backend

sample code

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function main() {
  // Create a new user
  const newUser = await prisma.user.create({
    data: {
      name: 'John Doe',
      email: 'john@example.com',
    },
  });
  console.log('Created new user:', newUser);

  // Retrieve all users
  const allUsers = await prisma.user.findMany();
  console.log('All users:', allUsers);
}

main()
  .catch((e) => {
    throw e;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

What is ZOD?

Zod is a TypeScript-first schema declaration and validation library. It allows you to define data schemas in a concise and expressive way, enabling runtime validation of data against those schemas. While Zod is primarily used for type validation in TypeScript projects, it is not directly related to databases like MongoDB.

sample code

import { z } from 'zod';
import { MongoClient } from 'mongodb';

// Define a Zod schema for your data
const userSchema = z.object({
  name: z.string(),
  email: z.string().email(),
  age: z.number().int().positive(),
});

async function insertUser(userData: any) {
  try {
    // Validate user data against the schema
    const validatedUserData = userSchema.parse(userData);

    // If validation succeeds, insert data into MongoDB
    const client = new MongoClient('mongodb://localhost:27017');
    await client.connect();
    const db = client.db('mydatabase');
    const result = await db.collection('users').insertOne(validatedUserData);
    console.log('User inserted:', result.insertedId);
    await client.close();
  } catch (error) {
    console.error('Validation failed:', error);
  }
}

// Example usage
insertUser({ name: 'John Doe', email: 'john@example.com', age: 30 });

Did you find this article valuable?

Support Thirumalai by becoming a sponsor. Any amount is appreciated!