@kokosro/ts-mongoose-wrapper
v0.3.0
Published
TypeScript wrapper for Mongoose with enhanced type safety and CLI model generator
Readme
ts-mongoose-wrapper
A TypeScript wrapper for Mongoose with enhanced type safety and a CLI model generator.
Installation
npm install @kokosro/ts-mongoose-wrapper mongooseCLI Model Generator
Generate TypeScript Mongoose models with a simple command:
npx ts-model-gen --name User \
--field "name:string:String:required" \
--field "email:string:String:required" \
--field "age:number:Number" \
--index "email:1:unique"CLI Options
| Option | Description |
| ------------- | ------------------------------------------------- |
| --name, -n | Model name (required) |
| --field, -f | Field definition (can be used multiple times) |
| --index, -i | Index definition (can be used multiple times) |
| --path, -p | Output path for models (default: ./src/db/models) |
Field Format
fieldName:tsType:schemaType[:required][:default=value][:ref=ModelName][:array]Examples
# Basic model
npx ts-model-gen -n Product \
-f "name:string:String:required" \
-f "price:number:Number:required" \
-f "description:string:String"
# Model with references
npx ts-model-gen -n Order \
-f "customer:ObjectId:Schema.Types.ObjectId:ref=User:required" \
-f "products:ObjectId:Schema.Types.ObjectId:ref=Product:array" \
-f "total:number:Number:required"# Basic usage
npx ts-model-gen --name Product \
--field "name:string:String:required" \
--field "price:number:Number:required" \
--field "description:string:String" \
--index "name:text:background"
# Short form options
npx ts-model-gen -n Product \
-f "name:string:String:required" \
-f "price:number:Number:required" \
-f "description:string:String" \
-i "name:text:background"Options
| Option | Description |
|--------|-------------|
| --name, -n | Model name (required) |
| --field, -f | Field definition (can be used multiple times) |
| --index, -i | Index definition (can be used multiple times) |
| --path, -p | Custom output path (default: ./src/db/models) |
Field Definition Format
fieldName:tsType:schemaType[:required][:default=value][:ref=ModelName][:array]Examples:
name:string:String:requiredprice:number:Number:required:default=0category:string:String:ref=CategoryisActive:boolean:Boolean:default=truetags:string:String:array(array of strings)references:ObjectId:Schema.Types.ObjectId:ref=User:array(array of User references)
Type Shortcuts
You can use these shortcuts for common types:
| Shortcut | TypeScript Type | Schema Type |
|----------|----------------|-------------|
| str | string | String |
| int, float, double | number | Number |
| bool | boolean | Boolean |
| id, oid, objectid | ObjectId | Schema.Types.ObjectId |
| obj, object | Record<string, any> | Schema.Types.Mixed |
For example, instead of:
userId:Types.ObjectId:Schema.Types.ObjectId:ref=UserYou can simply write:
userId:id::ref=UserOr even simpler when using references:
userId:::ref=UserThe script will automatically set the correct types when you specify a reference.
Using References to Other Models
When you specify a reference to another model using the ref=ModelName parameter:
- The script will verify if the referenced model exists
- It will automatically set the correct types (ObjectId for schema, proper model type for TypeScript)
- It will suggest reference fields based on naming patterns (fields ending with "Id" or "Ref")
- Arrays of references are supported with the
arrayparameter
Examples of model references with shortcuts:
# Create a Task model with a reference to User
npx ts-model-gen -n Task \
-f "title:str::required" \
-f "assignedTo:::ref=User" \
-f "watchers:::ref=User:array"Index Definition Format
fieldName:direction[:unique][:background]Examples:
email:1:uniquename:text:backgroundcreatedAt:-1
What the Script Does
- Creates a new model directory with the model name
- Generates three files:
index.ts- Exports from the modeltypes.ts- TypeScript type definitionsModelName.ts- Model implementation with schema
- Updates the constants file with the new model name
- Updates the models/index.ts file to include the new model
Examples
Creating a Product model with shortcuts
npx ts-model-gen -n Product \
-f "name:str::required" \
-f "price:number::required" \
-f "description:str" \
-f "category:::ref=Category" \
-f "isActive:bool::default=true" \
-f "tags:str::array" \
-i "name:text:background" \
-i "category:1" \
-i "price:-1"Creating an Order model with relationships
npx ts-model-gen -n Order \
-f "orderNumber:str::required" \
-f "customer:::ref=User:required" \
-f "products:::ref=Product:array:required" \
-f "total:number::required" \
-f "status:str::required:default='pending'" \
-i "orderNumber:1:unique" \
-i "customer:1" \
-i "status:1"Library Usage
import config from "./config";
import { createDatabase, Database } from "@kokosro/ts-mongoose-wrapper";
import { createDbModels, DbModels } from "./db"; // generated by script npx ts-model-gen
export const createDbInstance = async () => {
const db = await createDatabase<DbModels>({
connection: {
host: config.get('db.host'),
port: config.get('db.port'),
username: config.get('db.username'),
password: config.get('db.password'),
dbName: config.get('db.name')
},
createModels: createDbModels
});
return db;
}
export const getDbInstance = (() => {
let db: Database<DbModels>;
return async () => {
if (!db) {
db = await createDbInstance();
}
return db;
}
})()
