typed-mongo
v0.0.7
Published
A minimal, strongly-typed wrapper for the MongoDB Node.js driver.
Maintainers
Readme
typed-mongo
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-mongoBasic 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 missingIndex 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 modelsyncIndexes(options?)- Synchronize indexes for all registered modelsgetModels()- Get all registered modelsgetDb()- Get the underlying MongoDB database instance
Model
Models provide the following methods:
findOne(filter, options?)- Find a single documentfindCursor(filter, options?)- Returns a cursor (MongoDB standard)find(filter, options?)- Find multiple documents as an arrayinsertOne(doc, options?)- Insert a single documentinsertMany(docs, options?)- Insert multiple documentsupdateOne(filter, update, options?)- Update a single documentupdateMany(filter, update, options?)- Update multiple documentsreplaceOne(filter, replacement, options?)- Replace a documentdeleteOne(filter, options?)- Delete a single documentdeleteMany(filter, options?)- Delete multiple documentsfindOneAndUpdate(filter, update, options?)- Find and updatefindOneAndReplace(filter, replacement, options?)- Find and replacefindOneAndDelete(filter, options?)- Find and deletecountDocuments(filter?, options?)- Count documentsdistinct(key, filter?, options?)- Get distinct valuesaggregate(pipeline, options?)- Aggregation pipelinebulkWrite(operations, options?)- Bulk write operationssyncIndexes(options?)- Synchronize indexes for this modelgetCollection()- 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.
