Bridge Mongo

A fully typed mongoose ORM

README


Bridge Mongo


Bridge-mongo is a typed framework built on top of Mongoose, the popular MongoDB object-document mapping (ODM) library. It provides a type-safe approach to querying MongoDB databases that makes it almost impossible to write poorly constructed queries, all while using the same syntax as Mongoose.


👉 See more informations on mongo.bridge.codes 👈

Documentation


Full documentation for bridge-mongo can be found here.

Installation


  1. ```bash
  2. # npm
  3. npm install bridge-mongo
  4. # Yarn
  5. yarn add bridge-mongo
  6. # pnpm
  7. pnpm add bridge-mongo
  8. ```

Quickstart


Define your Schemas


Defining your schemas in bridge-mongo is just as easy as it is with Mongoose. You can define your schemas using Mongoose's schema syntax, and then use the createDB function to create your models.

When you use createDB, bridge-mongo will automatically create and register each model with Mongoose using the keys from your schema object as the model names. This means you can define all of your schemas in one place and have them automatically created and registered as models for you.

  1. ```ts twoslash title='index.ts'
  2. import { createDB, Schema, mongoose } from 'bridge-mongo';

  3. // Defining a User Schema
  4. const userSchema = new Schema({
  5.   name: { type: String, required: true },
  6.   email: String,
  7.   age: { type: Number, default: 18 },
  8.   job: { type: String, enum: ['developer', 'designer'] },
  9.   settings: {
  10.     isActive: Boolean,
  11.   },
  12. });

  13. // Defining a Post Schema
  14. const postSchema = new Schema(
  15.   {
  16.     text: { type: String, required: true },
  17.     userId: { type: mongoose.Types.ObjectId, req: true },
  18.     likes: Number,
  19.   },
  20.   { timestamps: true },
  21. );

  22. // The keys correspond to the model Name
  23. const DB = createDB({
  24.   User: userSchema,
  25.   Post: postSchema,
  26. });
  27. ```

Connect to MongoDB


Connecting to your MongoDB database using bridge-mongo is just as easy as it is with Mongoose. In fact, you can import mongoose directly from bridge-mongo and use its connect function to connect to your database.

  1. ```ts twoslash title='index.ts'
  2. import { mongoose } from 'bridge-mongo';

  3. const launch = async () => {
  4.     await mongoose.connect('Your MongoDB URL here');

  5.     console.log('Connected!')
  6. }

  7. launch();
  8. ```


Start enjoying type safety


You can enjoy the benefits of total type safety and guidance through TypeScript. The fully typed query results and error handling provided by bridge-mongo make it easy to write correct, efficient queries with confidence.

Read the documentation to get started or get a look to the examples below.

Some Queries examples:

  1. ```ts
  2. import { isError } from 'bridge-mongo';

  3. async () => {
  4.   const user = await DB.user.create({ name: 'Nab' });

  5.   const post = await DB.post.findOne({ userId: user._id }, {text: 1});

  6.   if (!isError(post)) console.log(post)


  7.   const posts = await DB.post.find({ likes: { $gt: 10 }});

  8.   const res = await DB.user.findByIdAndUpdate(user._id, { name: 'Neo' }, { projection: { name: 1 } })
  9. }
  10. ```

Some Aggregate examples:

  1. ```ts twoslash title='index.ts'
  2. async () => {
  3.   
  4.   // Fetching all users that have created post with their posts
  5.   const blogers = await DB.user
  6.     .aggregate()
  7.     .project({ name: 1 })
  8.     .lookup({ from: 'posts', localField: '_id', foreignField: 'userId' })
  9.     .match({ 'posts.0': { $exists: true } })
  10.     .exec();

  11.   // Fetching all posts from the last 24 hours with their author only if he's >= 21 years old

  12.   const yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);

  13.   const posts = await DB.post
  14.     .aggregate()
  15.     .project({ text: 1, createdAt: 1, userId: 1 })
  16.     .match({ createdAt: { $gt: yesterday } })
  17.     .lookup({ from: 'users', let: { userId: '$userId' }, as: 'user' }, (user, { userId }) =>
  18.       user
  19.         .match({ $expr: { $eq: ['$_id', userId] }, age: { $gte: 21 } })
  20.         .project({ name: 1 })
  21.         .limit(1),
  22.     )
  23.     .unwind('$user')
  24.     .unset('userId')
  25.     .exec();
  26. }
  27. ```


Bridge-mongo is constantly evolving and adding new features to provide a fully typed, robust, and easy-to-use interface for interacting with MongoDB. While many essential functions are already implemented, there are still many more features that can be added to meet specific use cases. If you are interested in contributing or discussing features that you'd like to see implemented, you can join the Bridge-mongo Discord server and be a part of the community.