Custom TypeScript definitions for Mongoose 8.x with support for flexible ID types.
Mongoose 8's official types enforce _id: Types.ObjectId in the Document type, which prevents using custom ID types like strings, UUIDs, or GUIDs. This package provides modified type definitions that allow _id to be any type, enabling full flexibility for ID management.
- Using string-based IDs (UUIDs, GUIDs, custom formats)
- Migrating from other databases with non-ObjectId primary keys
- Building systems that require specific ID formats
- Cross-platform applications with custom ID providers
npm install @digitaldefiance/mongoose-types mongoose@^8.20.0
# or
yarn add @digitaldefiance/mongoose-types mongoose@^8.20.0Add path mapping to your tsconfig.json:
{
"compilerOptions": {
"paths": {
"mongoose": ["node_modules/@digitaldefiance/mongoose-types/src/index.d.ts"]
}
}
}import { Document, Schema, model, Types } from 'mongoose';
// String-based IDs
interface IUser extends Document<string> {
_id: string;
username: string;
email: string;
}
const userSchema = new Schema({
_id: { type: String, required: true },
username: String,
email: String
});
const User = model<IUser>('User', userSchema);
// ObjectId (default behavior still works)
interface IRole extends Document<Types.ObjectId> {
_id: Types.ObjectId;
name: string;
}
// Custom ID type
interface IProduct extends Document<{ uuid: string; version: number }> {
_id: { uuid: string; version: number };
name: string;
}Document<T>generic parameterTdefault changed fromTypes.ObjectIdtoany- Updated JSDoc to clarify that
_idcan be ObjectId, string, or any custom type - All other Mongoose functionality remains unchanged
- Mongoose: ^8.20.0
- TypeScript: ^5.0.0
- Node.js: 18+
This package follows Mongoose's version numbers. Version 8.20.1 corresponds to Mongoose 8.20.1 types with custom ID support.
Contributions are welcome! Please open an issue or PR at https://github.com/Digital-Defiance/mongoose-types
MIT © Digital Defiance, Jessica Mulein
Part of the Express Suite ecosystem.