Skip to main content

Quickstart

Installation

Install bridge-mongo in your typescript project:

terminal
bash
npm install bridge-mongo
# or
yarn add bridge-mongo
# or
pnpm add bridge-mongo
terminal
bash
npm install bridge-mongo
# or
yarn add bridge-mongo
# or
pnpm 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.ts
ts
import { createDB, Schema, mongoose } from 'bridge-mongo';
 
// Defining a User Schema
const userSchema = new Schema({
name: { type: String, required: true },
email: String,
age: { type: Number, default: 18 },
job: { type: String, enum: ['developer', 'designer'] },
settings: {
isActive: Boolean,
},
});
 
// Defining a Post Schema
const postSchema = new Schema(
{
text: { type: String, required: true },
userId: { type: mongoose.Types.ObjectId, req: true },
likes: Number,
},
{ timestamps: true },
);
 
// The keys correspond to the model Name
const DB = createDB({
User: userSchema,
Post: postSchema,
});
index.ts
ts
import { createDB, Schema, mongoose } from 'bridge-mongo';
 
// Defining a User Schema
const userSchema = new Schema({
name: { type: String, required: true },
email: String,
age: { type: Number, default: 18 },
job: { type: String, enum: ['developer', 'designer'] },
settings: {
isActive: Boolean,
},
});
 
// Defining a Post Schema
const postSchema = new Schema(
{
text: { type: String, required: true },
userId: { type: mongoose.Types.ObjectId, req: true },
likes: Number,
},
{ timestamps: true },
);
 
// The keys correspond to the model Name
const DB = 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.ts
ts
import { mongoose } from 'bridge-mongo';
 
const launch = async () => {
await mongoose.connect('Your MongoDB URL here');
 
console.log('Connected!')
}
 
launch();
index.ts
ts
import { mongoose } from 'bridge-mongo';
 
const launch = async () => {
await mongoose.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.ts
ts
import { isError } from 'bridge-mongo';
 
async () => {
const user = await DB.user.create({ name: 'Nab' });
const user: { _id: mongoose.Schema.Types.ObjectId; age: number; name: string; }
const post = await DB.post.findOne({ userId: user._id }, {text: 1});
const post: { error: { status: 404; name: "Post not found"; }; } | { _id: mongoose.Schema.Types.ObjectId; text: string; }
if (!isError(post)) console.log(post)
const post: { _id: mongoose.Schema.Types.ObjectId; text: string; }
 
const posts = await DB.post.find({ likes: { $gt: 10 }});
const posts: { _id: mongoose.Schema.Types.ObjectId; text: string; createdAt: Date; updatedAt: Date; userId?: mongoose.Schema.Types.ObjectId | undefined; likes?: number | undefined; }[]
 
const res = await DB.user.findByIdAndUpdate(user._id, { name: 'Neo' }, { projection: { name: 1 } })
const res: { error: { status: 404; name: "User not found"; }; } | { _id: mongoose.Schema.Types.ObjectId; name: string; }
}
index.ts
ts
import { isError } from 'bridge-mongo';
 
async () => {
const user = await DB.user.create({ name: 'Nab' });
const user: { _id: mongoose.Schema.Types.ObjectId; age: number; name: string; }
const post = await DB.post.findOne({ userId: user._id }, {text: 1});
const post: { error: { status: 404; name: "Post not found"; }; } | { _id: mongoose.Schema.Types.ObjectId; text: string; }
if (!isError(post)) console.log(post)
const post: { _id: mongoose.Schema.Types.ObjectId; text: string; }
 
const posts = await DB.post.find({ likes: { $gt: 10 }});
const posts: { _id: mongoose.Schema.Types.ObjectId; text: string; createdAt: Date; updatedAt: Date; userId?: mongoose.Schema.Types.ObjectId | undefined; likes?: number | undefined; }[]
 
const res = await DB.user.findByIdAndUpdate(user._id, { name: 'Neo' }, { projection: { name: 1 } })
const res: { error: { status: 404; name: "User not found"; }; } | { _id: mongoose.Schema.Types.ObjectId; name: string; }
}

Some Aggregate examples:

index.ts
ts
async () => {
// Fetching all users that have created post with their posts
const blogers = await DB.user
.aggregate()
.project({ name: 1 })
.lookup({ from: 'posts', localField: '_id', foreignField: 'userId' })
.match({ 'posts.0': { $exists: true } })
.exec();
 
console.log(blogers);
const blogers: { _id: mongoose.Schema.Types.ObjectId; name: string; posts: { createdAt: Date; updatedAt: Date; _id: mongoose.Schema.Types.ObjectId; text: string; userId?: mongoose.Schema.Types.ObjectId | undefined; likes?: number | undefined; }[]; }[]
 
// Fetching all posts from the last 24 hours with their author only if he's >= 21 years old
 
const yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
 
const posts = await DB.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);
const posts: { text: string; _id: mongoose.Schema.Types.ObjectId; user: { _id: mongoose.Schema.Types.ObjectId; name: string; }; createdAt: Date; }[]
 
}
index.ts
ts
async () => {
// Fetching all users that have created post with their posts
const blogers = await DB.user
.aggregate()
.project({ name: 1 })
.lookup({ from: 'posts', localField: '_id', foreignField: 'userId' })
.match({ 'posts.0': { $exists: true } })
.exec();
 
console.log(blogers);
const blogers: { _id: mongoose.Schema.Types.ObjectId; name: string; posts: { createdAt: Date; updatedAt: Date; _id: mongoose.Schema.Types.ObjectId; text: string; userId?: mongoose.Schema.Types.ObjectId | undefined; likes?: number | undefined; }[]; }[]
 
// Fetching all posts from the last 24 hours with their author only if he's >= 21 years old
 
const yesterday = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
 
const posts = await DB.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);
const posts: { text: string; _id: mongoose.Schema.Types.ObjectId; user: { _id: mongoose.Schema.Types.ObjectId; name: string; }; createdAt: Date; }[]
 
}
info

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.