Mongoloquent ORM

website·Indexed 30 days ago

https://mongoloquent.com

An ORM for JavaScript and TypeScript that provides model class generation, query building, and serialization. It supports various model relationships including One to One, One to Many, Belongs To, Has Many Through, and Many to Many, as well as polymorphic relationships. Documentation covers versions v1.1.x, v2.x.x, v3.x.x, v4.x.x, and Next, including integrations with NestJS.

Tokens
53.2K
Snippets
368
Records
407
Agent score
49%

What's inside Mongoloquent

  1. Overview of Mongoloquent features

    Mongoloquent is an MIT-licensed ORM for MongoDB designed to provide an intuitive and expressive syntax for database interactions. Key capabilities include:

    • Type Safety: Ensures MongoDB queries match expected data structures.
    • Relationship Management: Supports various relationship types for flexible database modeling.
    • Flexible Access: Allows developers to interact with the database using either an ORM approach or a Query Builder.
    • Multi-Database Support: Enables the management of multiple simultaneous database connections.
    • Test Environment Support: Provides built-in facilitation for testing functionality within a dedicated test environment.
  2. Overview of Mongoloquent MongoDB ORM

    v2.x.x
    Mongoloquent is a lightweight MongoDB ORM library for JavaScript and TypeScript, designed to provide an intuitive and expressive syntax inspired by Laravel Eloquent. It is intended for use in Node.js environments and supports multiple relationship types and test environment configurations.
  3. Overview of Mongoloquent MongoDB ORM

    v1.1.x
    Mongoloquent is a lightweight MongoDB ORM library for JavaScript and TypeScript designed to provide an intuitive and expressive syntax similar to Laravel Eloquent. It is intended for use in Node.js environments and supports multiple relationship types and test environment configurations.
  4. Work with Mongoloquent Collection results

    In Mongoloquent, any method that returns multiple model results (such as the get method or results accessed via a relationship) returns an instance of the Collection class. These collections extend the base collection class, providing a fluent interface for map/reduce operations and allowing them to be iterated over like standard JavaScript arrays.
    import User from './Models/User';
    
    const users = await User.where('active', true).get();
    
    for (const user of users) {
      console.log(user.name);
    }
  5. Work with Mongoloquent Collection results

    In Mongoloquent v4.x.x, any method that returns multiple model results (such as the get method or relationship accessors) returns an instance of the Collection class. This class extends the base Laravel collection, providing a fluent interface for map/reduce operations and allowing the collection to be used as an iterator (similar to a standard JavaScript array).
    import User from './Models/User';
    
    // .get() returns a Mongoloquent Collection
    const users = await User.where('active', true).get();
    
    // Collections can be iterated over like arrays
    for (const user of users) {
      console.log(user.name);
    }
  6. Perform collection joins using lookup

    The lookup method implements MongoDB's aggregation lookup to join documents from another collection. You can chain multiple lookup calls to join multiple collections in a single query.
    const users = await DB.collection<IUser>("users")
      .lookup({
        from: "posts",
        localField: "_id",
        foreignField: "userId",
        as: "posts"
      })
      .lookup({
        from: "orders",
        localField: "_id",
        foreignField: "userId",
        as: "orders"
      })
      .get();
  7. Manage database transactions

    Use DB.transaction() to execute a set of operations atomically. If an exception occurs within the closure, the transaction is automatically rolled back; otherwise, it is committed.

    Key constraints and features:

    • Operations within the transaction must pass the session object as an option to the query method.
    • Transactions only work within the same connection and database.
    • You can specify a custom connection for the transaction using DB.connection(uri).transaction().
    • Deadlocks can be handled by passing a retries option in the second argument.
    import { DB } from '@mongoloquent/core';
    
    // Basic transaction with deadlock retries
    await DB.transaction(async (session) => {
      await DB
        .collection("users")
        .where("name", "John Doe")
        .update({ votes: 1 }, { session });
    
      await DB
        .collection("posts")
        .where("title", "Hello World")
        .delete({ session });
    }, { retries: 5 });
    
    // Transaction with custom connection
    await DB.connection("mongodb://localhost:27017").transaction(async (session) => {
      await DB.collection("users").update({ votes: 1 }, { session });
    });
  8. Permanently delete models from the database

    v2.x.x
    To bypass soft deletion and physically remove a record from the database collection, use the forceDelete() method. This can be called on a specific model instance or combined with query methods to delete multiple records.
    import User from "./yourPath/User";
    
    // Permanently remove a model
    await User.forceDelete();
    
    // Permanently remove models matching a query
    await User.where("age", 50).forceDelete();
  9. Create and use Mongoloquent Collections

    v3.x.x
    The Collection class is a fluent, immutable wrapper for arrays of data, allowing for chained mapping and reducing operations. Every Collection method returns a new instance, preserving the original data. Mongoloquent query results are automatically returned as Collection instances.
    import { collect } from "mongoloquent";
    
    // Create a collection using the collect helper
    const collection = collect(["Ajat", "Udin", null]);
    
    // Chain methods for fluent manipulation
    const result = collection
      .where("foo", "Ajat")
      .map((item) => item.toUpperCase());
  10. Implement One-to-Many Polymorphic relationships in Mongoloquent

    v2.x.x
    A one-to-many polymorphic relationship allows a child model to belong to more than one type of model using a single association. This is achieved by adding two specific fields to the child collection: an ID field and a Type field (e.g., commentableId and commentableType).
    // Example Collection Structure
    posts
      _id - ObjectId
      title - string
    
    videos
      _id - ObjectId
      title - string
    
    comments
      _id - ObjectId
      body - text
      commentableId - ObjectId // Stores the _id of the parent (Post or Video)
      commentableType - string  // Stores the type of the parent model
  11. Manage database transactions and deadlocks

    v3.x.x

    Use DB.transaction() to execute a set of operations atomically. The transaction automatically commits if the closure succeeds and rolls back if an exception is thrown.

    Key constraints and features:

    • Operations within the transaction must pass the session object as an option to the query method.
    • Transactions only work within the same connection and database.
    • You can specify a custom connection URI before calling .transaction().
    • Deadlocks can be handled by passing a retries option in the second argument of the transaction method.
    import { DB } from 'mongoloquent';
    
    // Basic transaction with deadlock retry logic
    await DB.transaction(async (session) => {
      await DB
        .collection("users")
        .where("name", "John Doe")
        .update({ votes: 1 }, { session });
    
      await DB
        .collection("posts")
        .where("title", "Hello World")
        .delete({ session });
    }, { retries: 5 });
    
    // Transaction with a custom connection
    await DB.connection("mongodb://localhost:27017").transaction(async (session) => {
      await DB.collection("users").update({ name: "Jane" }, { session });
    });
  12. Use multiple database connections

    v3.x.x
    If an application requires multiple database connections, use the connection and database methods on the DB class to specify the URI and database name for a specific query chain.
    import { DB, IMongoloquentSchema, IMongoloquentTimestamps } from 'mongoloquent';
    
    interface IUser extends IMongoloquentSchema, IMongoloquentTimestamps {
      name: string;
    }
    
    const users = await DB.connection("mongodb://another-uri:27017")
      .database("anotherDatabaseName")
      .collection<IUser>("users")
      .get();