Quickstart
Installation
Install bridge-mongo
in your typescript project:
terminalbash
npm install bridge-mongo# oryarn add bridge-mongo# orpnpm add bridge-mongo
terminalbash
npm install bridge-mongo# oryarn add bridge-mongo# orpnpm add bridge-mongo
Define your Schemas
Defining your schemas in bridge-mongo is just as easy as it is with Mongoose. You 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.
index.tsts
import {createDB ,Schema ,mongoose } from 'bridge-mongo';// Defining a User SchemaconstuserSchema = newSchema ({name : {type :String ,required : true },String ,age : {type :Number ,default : 18 },job : {type :String ,enum : ['developer', 'designer'] },settings : {isActive :Boolean ,},});// Defining a Post SchemaconstpostSchema = newSchema ({text : {type :String ,required : true },userId : {type :mongoose .Types .ObjectId ,req : true },likes :Number ,},{timestamps : true },);// The keys correspond to the model NameconstDB =createDB ({User :userSchema ,Post :postSchema ,});
index.tsts
import {createDB ,Schema ,mongoose } from 'bridge-mongo';// Defining a User SchemaconstuserSchema = newSchema ({name : {type :String ,required : true },String ,age : {type :Number ,default : 18 },job : {type :String ,enum : ['developer', 'designer'] },settings : {isActive :Boolean ,},});// Defining a Post SchemaconstpostSchema = newSchema ({text : {type :String ,required : true },userId : {type :mongoose .Types .ObjectId ,req : true },likes :Number ,},{timestamps : true },);// The keys correspond to the model NameconstDB =createDB ({User :userSchema ,Post :postSchema ,});
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.
index.tsts
import {mongoose } from 'bridge-mongo';constlaunch = async () => {awaitmongoose .connect ('Your MongoDB URL here');console .log ('Connected!')}launch ();
index.tsts
import {mongoose } from 'bridge-mongo';constlaunch = async () => {awaitmongoose .connect ('Your MongoDB URL here');console .log ('Connected!')}launch ();
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:
index.tsts
import {isError } from 'bridge-mongo';async () => {constuser = awaitDB .user .create ({name : 'Nab' });constpost = awaitDB .post .findOne ({userId :user ._id }, {text : 1});if (!isError (post ))console .log (post )constposts = awaitDB .post .find ({likes : {$gt : 10 }});constres = awaitDB .user .findByIdAndUpdate (user ._id , {name : 'Neo' }, {projection : {name : 1 } })}
index.tsts
import {isError } from 'bridge-mongo';async () => {constuser = awaitDB .user .create ({name : 'Nab' });constpost = awaitDB .post .findOne ({userId :user ._id }, {text : 1});if (!isError (post ))console .log (post )constposts = awaitDB .post .find ({likes : {$gt : 10 }});constres = awaitDB .user .findByIdAndUpdate (user ._id , {name : 'Neo' }, {projection : {name : 1 } })}
Some Aggregate examples:
index.tsts
async () => {// Fetching all users that have created post with their postsconstblogers = awaitDB .user .aggregate ().project ({name : 1 }).lookup ({from : 'posts',localField : '_id',foreignField : 'userId' }).match ({ 'posts.0': {$exists : true } }).exec ();console .log (blogers );// Fetching all posts from the last 24 hours with their author only if he's >= 21 years oldconstyesterday = newDate (newDate ().getTime () - 24 * 60 * 60 * 1000);constposts = awaitDB .post .aggregate ().project ({text : 1,createdAt : 1,userId : 1 }).match ({createdAt : {$gt :yesterday } }).lookup ({from : 'users',let : {userId : '$userId' },as : 'user' }, (user , {userId }) =>user .match ({$expr : {$eq : ['$_id',userId ] },age : {$gte : 21 } }).project ({name : 1 }).limit (1),).unwind ('$user').unset ('userId').exec ();console .log (posts );}
index.tsts
async () => {// Fetching all users that have created post with their postsconstblogers = awaitDB .user .aggregate ().project ({name : 1 }).lookup ({from : 'posts',localField : '_id',foreignField : 'userId' }).match ({ 'posts.0': {$exists : true } }).exec ();console .log (blogers );// Fetching all posts from the last 24 hours with their author only if he's >= 21 years oldconstyesterday = newDate (newDate ().getTime () - 24 * 60 * 60 * 1000);constposts = awaitDB .post .aggregate ().project ({text : 1,createdAt : 1,userId : 1 }).match ({createdAt : {$gt :yesterday } }).lookup ({from : 'users',let : {userId : '$userId' },as : 'user' }, (user , {userId }) =>user .match ({$expr : {$eq : ['$_id',userId ] },age : {$gte : 21 } }).project ({name : 1 }).limit (1),).unwind ('$user').unset ('userId').exec ();console .log (posts );}
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.