Exapedia / Tools / JavaScript MongoDB libraries JavaScript MongoDB libraries Updated Nov 2026
JavaScript MongoDB libraries connect Node.js applications to MongoDB and read and write its documents. An ODM or ORM layers schemas, validation, and typed models over the official driver's collection API. These libraries let apps and backend services store user records, content, and event data as JSON-like documents.
Popularity Capabilities MongoDB Node.js driver Mongoose TypeORM Typegoose MikroORM FAQ Popularity MongoDB Node.js Driver has the most monthly downloads in this comparison, at 83.5M .
Library Monthly downloads Stars Last release License MongoDB Node.js driver 83.5M
10.2K Nov 2026 Apache-2.0 Mongoose 35.2M
27.4K Nov 2026 MIT TypeORM 26.9M
Not on GitHub Nov 2026 MIT Typegoose 1.2M
2.3K Sep 2026 MIT MikroORM 223.8K
9.3K Nov 2026 MIT Downloads: npm , last thirty days. Stars and releases: GitHub. Amber: no release in over a year.
Libraries and code examples Connects Node.js applications directly to MongoDB with the official driver.
Downloads / mo 83.5M
Stars 10.2K
Last release 7.9.0
License Apache-2.0 Strengths Reuses database connections . Each MongoClient maintains connection pools for its servers. Retries supported transaction failures . The Convenient Transaction API includes transaction retry handling. Limitations Transactions run operations sequentially . Await each transaction operation instead of using Promise.all. Core transactions need error handling . Implement retries yourself when using the Core API. $ npm install mongodb@7.9.0 Copy
import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb://127.0.0.1:27017/library_example');
await client.connect();
const user = await client.db().collection('users').findOne({ name: 'Ada' });
await client.close();
Adds schemas, document models, and reference population to MongoDB applications.
Downloads / mo 35.2M
Stars 27.4K
Last release 9.12.2
License MIT Strengths Loads referenced documents . Use populate to replace references with documents from other collections. Tracks rolled-back document changes . Connection.transaction restores change tracking after an aborted save. Limitations Queries can wait for connections . Disable bufferCommands to expose missing connections instead of buffering calls. Populated fields cannot filter parents . Filtering populated authors does not filter the matching stories. $ npm install mongoose@9.12.2 Copy
import mongoose from 'mongoose';
await mongoose.connect('mongodb://127.0.0.1:27017/library_example');
const User = mongoose.model('User', new mongoose.Schema({ name: String }));
const user = await User.findOne({ name: 'Ada' });
await mongoose.disconnect();
Mongoose examples From open-source projects on GitHub export const connect: Connect = async function connect(
this: MongooseAdapter,
options = {
hotReload: false,
},
) {
const { hotReload } = options
if (this.url === false) {
return
}
if (typeof this.url !== 'string') {
throw new Error('Error: missing MongoDB connection URL.')
}
const urlToConnect = this.url
const connectionOptions: ConnectOptions = {
autoIndex: true,
...this.connectOptions,
}
if (hotReload) {
connectionOptions.autoIndex = false
}
try {
if (!this.connection) {
this.connection = await mongoose.createConnection(urlToConnect, connectionOptions).asPromise()
if (this.afterCreateConnection) {
await this.afterCreateConnection(this)
}
}
await this.connection.openUri(urlToConnect, connectionOptions)
if (this.afterOpenConnection) {
await this.afterOpenConnection(this)
}
if (this.useAlternativeDropDatabase) {
if (this.connection.db) {
// Firestore doesn't support dropDatabase, so we monkey patch
// dropDatabase to delete all documents from all collections instead
this.connection.db.dropDatabase = async function (): Promise<boolean> {
const existingCollections = await this.listCollections().toArray()
await Promise.all(
existingCollections.map(async (collectionInfo) => {
const collection = this.collection(collectionInfo.name)
await collection.deleteMany({})
}),
)
return true
}
this.connection.dropDatabase = async function () {
await this.db?.dropDatabase()
}
}
}
// If we are running a replica set with MongoDB Memory Server,
// wait until the replica set elects a primary before proceeding
if (this.mongoMemoryServer) {
this.payload.logger.info(
'Waiting for MongoDB Memory Server replica set to elect a primary...',
)
await new Promise((resolve) => setTimeout(resolve, 2000))
}
if (!this.connection.getClient().options.replicaSet) {
this.transactionOptions = false
this.beginTransaction = defaultBeginTransaction()
}
if (!hotReload) {
if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
this.payload.logger.info('---- DROPPING DATABASE ----')
await this.connection.dropDatabase()
this.payload.logger.info('---- DROPPED DATABASE ----')
}
}
if (this.ensureIndexes) {
await Promise.all(
[
...this.payload.config.collections.flatMap((collection) => [
this.collections[collection.slug],
this.versions[collection.slug],
]),
...this.payload.config.globals.map((global) => this.versions[global.slug]),
].map(async (model) => {
await model?.ensureIndexes()
}),
)
}
if (process.env.NODE_ENV === 'production' && this.prodMigrations) {
await this.migrate({ migrations: this.prodMigrations as unknown as Migration[] })
}
} catch (err) {
let msg = `Error: cannot connect to MongoDB.`
if (typeof err === 'object' && err && 'message' in err && typeof err.message === 'string') {
msg = `${msg} Details: ${err.message}`
}
this.payload.logger.error({
err,
msg,
})
throw new Error(`Error: cannot connect to MongoDB: ${msg}`)
}
}
Show full example Maps classes and entities to MongoDB through a repository interface with basic MongoDB support.
Downloads / mo 26.9M
Last release 1.1.3
License MIT $ npm install typeorm@1.1.3 mongodb@7.9.0 reflect-metadata@0.2.2 Copy
import 'reflect-metadata';
import { DataSource, Entity, Column, ObjectIdColumn } from 'typeorm';
import { ObjectId } from 'mongodb';
@Entity()
class User {
@ObjectIdColumn() id!: ObjectId;
@Column() name!: string;
}
const db = new DataSource({ type: 'mongodb', url: 'mongodb://127.0.0.1:27017/library_example', entities: [User] });
await db.initialize();
const user = await db.getMongoRepository(User).findOneBy({ name: 'Ada' });
await db.destroy();
TypeORM examples From open-source projects on GitHub async initialize(AppDataSource: DataSource, componentNodes: IComponentNodesPool) {
this.deployedWorkflows = {}
this.AppDataSource = AppDataSource
const workflows = await this.AppDataSource.getMongoRepository(Workflow).find()
for (let i = 0; i < workflows.length; i += 1) {
const workflow = workflows[i]
if (workflow.deployed) {
try {
const flowDataString = workflow.flowData
const flowData: IReactFlowObject = JSON.parse(flowDataString)
const reactFlowNodes = flowData.nodes as IReactFlowNode[]
const reactFlowEdges = flowData.edges as IReactFlowEdge[]
const workflowShortId = workflow.shortId
const { graph, nodeDependencies } = constructGraphs(reactFlowNodes, reactFlowEdges)
const { faultyNodeLabels, startingNodeIds } = getStartingNode(nodeDependencies, reactFlowNodes)
// If there are faulty nodes and deployed is active, update deployed to false
if (faultyNodeLabels.length) {
const body = {
deployed: false
}
const updateWorkflow = new Workflow()
Object.assign(updateWorkflow, body)
AppDataSource.getMongoRepository(Workflow).merge(workflow, updateWorkflow)
await AppDataSource.getMongoRepository(Workflow).save(workflow)
continue
}
await this.add(startingNodeIds, graph, reactFlowNodes, componentNodes, workflowShortId)
} catch (e) {
throw new Error(`Error initializing workflow ${workflow.shortId}: ${e}`)
}
}
}
}
Show full example Defines Mongoose models through TypeScript classes and decorators.
Downloads / mo 1.2M
Stars 2.3K
Last release 13.5.0
License MIT Strengths Defines models with TypeScript classes . Use decorated class properties to build Mongoose models. Narrows populated reference types . Use isDocument to check references before accessing populated fields. Limitations Requires legacy TypeScript decorators . Enable experimentalDecorators; Stage 3 decorators are unsupported. Needs care with esbuild . Use a compiler that emits decorator metadata. $ npm install @typegoose/typegoose@13.5.0 mongoose@~9.9.5 reflect-metadata@0.2.2 Copy
import 'reflect-metadata';
import mongoose from 'mongoose';
import { prop, getModelForClass } from '@typegoose/typegoose';
class User {
@prop({ type: () => String }) name?: string;
}
await mongoose.connect('mongodb://127.0.0.1:27017/library_example');
const UserModel = getModelForClass(User);
const user = await UserModel.findOne({ name: 'Ada' });
await mongoose.disconnect();
Typegoose examples From open-source projects on GitHub export function createTypegooseProviders(connectionName: string,
models: TypegooseClassWithOptions[] = []): FactoryProvider[] {
const connectionToken = getConnectionToken(connectionName);
const buildProvider = ({ name }: TypegooseClass, modelFactory: ModelFactory) => ({
provide: getModelToken(name),
useFactory: modelFactory,
inject: [connectionToken],
});
const createDiscriminatorFactoryFrom = (parentFactory: ModelFactory) =>
(discriminatorDefinition: TypegooseClass | TypegooseDiscriminator) => {
if (isTypegooseClass(discriminatorDefinition)) {
return buildProvider(discriminatorDefinition, (connection: Connection) =>
getDiscriminatorModelForClass(
parentFactory(connection),
discriminatorDefinition
)
);
}
const { typegooseClass, discriminatorId } = discriminatorDefinition;
return buildProvider(typegooseClass, (connection: Connection) =>
getDiscriminatorModelForClass(
parentFactory(connection),
typegooseClass,
discriminatorId
)
);
};
return models.reduce(
(providers, { typegooseClass, schemaOptions = {}, discriminators = [] }) => {
const modelFactory = (connection: Connection) => getModelForClass(
typegooseClass,
{ existingConnection: connection, schemaOptions },
);
const modelProvider = buildProvider(typegooseClass, modelFactory);
const discriminatorProviders = discriminators.map(createDiscriminatorFactoryFrom(modelFactory));
return [...providers, modelProvider, ...discriminatorProviders];
},
[],
);
}
Show full example Maps MongoDB documents to entities with change tracking and a unit of work.
Downloads / mo 223.8K
Stars 9.3K
Last release 7.2.10
License MIT Strengths Groups entity changes for saving . Create related entities and save their pending changes with flush. Loads related entities . Use populate when fetching authors with their books. Limitations Transactions require a replica set . Use a replica-set deployment before enabling MongoDB transactions. Implicit transactions are opt-in . Enable implicitTransactions or use an explicit transactional block. $ npm install @mikro-orm/mongodb@7.2.10 Copy
import { MikroORM, EntitySchema } from '@mikro-orm/mongodb';
const User = new EntitySchema({
name: 'User',
properties: {
_id: { type: 'ObjectId', primary: true },
name: { type: 'string' },
},
});
const orm = await MikroORM.init({ entities: [User], dbName: 'library_example', clientUrl: 'mongodb://127.0.0.1:27017' });
const user = await orm.em.fork().findOne('User', { name: 'Ada' });
await orm.close();
MikroORM examples From open-source projects on GitHub export async function disableFeed(orm: MikroORM, feedId: string, reason: string) {
try {
const repo = orm.em.getRepository(Feed)
await repo.nativeUpdate({
_id: new ObjectId(feedId)
}, {
disabled: reason
})
} catch (err) {
const errorMessage = `Failed to disable feed ${feedId}: ${(err as Error).message}`
log.error(errorMessage)
logDatadog('error', errorMessage, {
stack: (err as Error).stack
})
}
}
Show full example For coding agents
Found your MongoDB library? Help your agent use it. Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.
Claude Code Cursor Codex VS Code Devin Devin Desktop Gemini CLI OpenCode
Run in your terminal
claude plugin install exa@claude-plugins-official Copy Add to ~/.cursor/mcp.json
{
"mcpServers": {
"exa": {
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy Open in your browser, then install the Exa plugin
https://chatgpt.com/plugins/exa Copy Add to .vscode/mcp.json
{
"servers": {
"exa": {
"type": "http",
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy In Devin, open Customize, then MCPs, and add a custom HTTP server with this URL
https://mcp.exa.ai/mcp Copy Add to ~/.config/devin/mcp_config.json
{
"mcpServers": {
"exa": {
"serverUrl": "https://mcp.exa.ai/mcp"
}
}
} Copy Add to ~/.gemini/settings.json
{
"mcpServers": {
"exa": {
"httpUrl": "https://mcp.exa.ai/mcp"
}
}
} Copy Add to opencode.json
{
"mcp": {
"exa": {
"type": "remote",
"url": "https://mcp.exa.ai/mcp"
}
}
} Copy