npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

typed-mongo

v0.0.7

Published

A minimal, strongly-typed wrapper for the MongoDB Node.js driver.

Readme

typed-mongo

CI npm version License: MIT

typed-mongo is an extremely thin wrapper for the MongoDB Node.js driver that provides powerful type inference and declarative index creation while maintaining the performance of the original MongoDB client. Inspired by the papr library, typed-mongo takes a similar approach but focuses on simplicity and performance.

Features

  • 🔄 Extremely thin wrapper around the MongoDB Node.js driver
  • 🎯 Smart type inference
  • 🔄 No custom schema definitions required
  • ⚡ Superior performance
  • 📝 Declarative index creation

Installation

npm install typed-mongo
# or
pnpm add typed-mongo
# or
yarn add typed-mongo

Basic Usage

import { MongoClient, ObjectId } from 'mongodb';
import { TypedMongo } from 'typed-mongo';

// Define your schema
type UserSchema = {
  _id: ObjectId;
  name: string;
  age: number;
  email?: string;
  profile?: {
    bio: string;
    avatar?: string;
  };
};

// Connect to MongoDB
const mongoClient = new MongoClient('mongodb://localhost:27017', { ignoreUndefined: true });
await mongoClient.connect();
const db = mongoClient.db('myapp');

// Initialize typed-mongo
const typedMongo = new TypedMongo(db);

// Create a type-safe model
const User = typedMongo.model<UserSchema>('users');

// Insert a document with type-safe
await User.insertOne({
  name: 'Alice',
  age: 25,
  email: '[email protected]'
});

// user is typed as UserSchema | null
const user = await User.findOne({ name: 'Alice' });

// usersWithProjection is typed as { _id: ObjectId; name: string; }[]
const usersWithProjection = await User.find(
  {},
  { projection: { name: 1 } }
);

Type Error Examples

TypeScript will catch these errors at compile time:

// ❌ Type error: non-existent field
await User.findOne({ 
  nonExistentField: 'value' 
});
// Error: 'nonExistentField' does not exist in type UserSchema

// ❌ Type error: wrong type
await User.findOne({ 
  age: 'thirty' // age should be number
});
// Error: Type 'string' is not assignable to type 'number'

// ❌ Type error: missing required field
await User.insertOne({
  _id: 'user1',
  // name field is missing
  age: 25
});
// Error: Property 'name' is missing

Index Management

typed-mongo provides declarative index creation.

const User = typedMongo.model<UserSchema>('users', {
  indexes: [
    { key: { email: 1 }, unique: true },
    { key: { name: 1 } },
  ]
});

// Create indexes and drop obsolete ones (Recommended)
await User.syncIndexes({ dropObsolete: true });

// Sync indexes (safe: only creates new indexes, never drops)
await User.syncIndexes();

// otherwise, you can sync indexes for all models
await typedMongo.syncIndexes({ dropObsolete: true });

API Reference

TypedMongo

const typedMongo = new TypedMongo(db: Db);

Methods

  • model<TSchema>(collectionName: string, options?: ModelOptions) - Create a type-safe model
  • syncIndexes(options?) - Synchronize indexes for all registered models
  • getModels() - Get all registered models
  • getDb() - Get the underlying MongoDB database instance

Model

Models provide the following methods:

  • findOne(filter, options?) - Find a single document
  • findCursor(filter, options?) - Returns a cursor (MongoDB standard)
  • find(filter, options?) - Find multiple documents as an array
  • insertOne(doc, options?) - Insert a single document
  • insertMany(docs, options?) - Insert multiple documents
  • updateOne(filter, update, options?) - Update a single document
  • updateMany(filter, update, options?) - Update multiple documents
  • replaceOne(filter, replacement, options?) - Replace a document
  • deleteOne(filter, options?) - Delete a single document
  • deleteMany(filter, options?) - Delete multiple documents
  • findOneAndUpdate(filter, update, options?) - Find and update
  • findOneAndReplace(filter, replacement, options?) - Find and replace
  • findOneAndDelete(filter, options?) - Find and delete
  • countDocuments(filter?, options?) - Count documents
  • distinct(key, filter?, options?) - Get distinct values
  • aggregate(pipeline, options?) - Aggregation pipeline
  • bulkWrite(operations, options?) - Bulk write operations
  • syncIndexes(options?) - Synchronize indexes for this model
  • getCollection() - Get the underlying MongoDB collection

Performance

typed-mongo is designed as a thin wrapper around the MongoDB native driver, providing superior performance compared to heavy ORMs like Mongoose:

  • Minimal overhead: No unnecessary abstraction layers
  • Native MongoDB performance: Near-native driver speed
  • Memory efficient: No additional schema validation or middleware overhead

Why Choose typed-mongo?

vs Mongoose

  • ✅ Better performance
  • ✅ Superior type inference
  • ✅ Smaller bundle size
  • ✅ No duplicate schema definitions

vs Native MongoDB Driver

  • ✅ Full type safety
  • ✅ Better developer experience
  • ✅ Early type error detection
  • ✅ IDE autocomplete support

Trusted by

typed-mongo is trusted by Codatum.

License

MIT

Contributing

Pull requests are welcome! For major changes, please open an issue first to discuss what you would like to change.

Support

If you encounter any issues or have feature requests, please open an issue on GitHub.