![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
@typegoose/typegoose
Advanced tools
@typegoose/typegoose is a library that allows you to define Mongoose models using TypeScript classes. It provides a more type-safe and object-oriented way to interact with MongoDB, leveraging TypeScript's type system to ensure that your data models are consistent and well-defined.
Defining Models
This feature allows you to define Mongoose models using TypeScript classes. The `@prop` decorator is used to define schema properties, and `getModelForClass` is used to create the Mongoose model.
const { prop, getModelForClass } = require('@typegoose/typegoose');
class User {
@prop({ required: true })
public name!: string;
@prop()
public age?: number;
}
const UserModel = getModelForClass(User);
Type Safety
Typegoose leverages TypeScript's type system to provide type safety. This ensures that the properties of your models are consistent with the types defined in your TypeScript classes.
const user = new UserModel({ name: 'John Doe', age: 30 });
console.log(user.name); // TypeScript will ensure 'name' is a string
console.log(user.age); // TypeScript will ensure 'age' is a number or undefined
Hooks and Middleware
Typegoose supports Mongoose hooks and middleware, allowing you to run custom logic before and after certain operations. This is useful for tasks like validation, logging, and more.
const { pre, post } = require('@typegoose/typegoose');
@pre<User>('save', function(next) {
console.log('Before saving:', this);
next();
})
@post<User>('save', function(doc) {
console.log('After saving:', doc);
})
class User {
@prop({ required: true })
public name!: string;
@prop()
public age?: number;
}
const UserModel = getModelForClass(User);
Mongoose is a MongoDB object modeling tool designed to work in an asynchronous environment. It provides a schema-based solution to model your application data. While Mongoose is powerful and flexible, it lacks the type safety and TypeScript integration that Typegoose offers.
TypeORM is an ORM for TypeScript and JavaScript (ES7, ES6, ES5). It supports multiple databases including MongoDB. TypeORM provides a more general ORM solution compared to Typegoose, which is specifically designed for MongoDB and Mongoose.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server. While it is not specifically designed for MongoDB, it offers a robust and flexible ORM solution for SQL databases. It does not provide the same level of TypeScript integration as Typegoose.
(These badges are from typegoose:master)
Define Mongoose models using TypeScript classes
Migration Guides:
(Date format: dd-mm-yyyy
)
25-11-2023
)27-03-2023
)12-12-2022
)22-09-2021
)28-07-2021
)01-04-2020
)30-09-2019
)import { prop, getModelForClass } from '@typegoose/typegoose';
import mongoose from 'mongoose';
class User {
@prop()
public name?: string;
@prop({ type: () => [String] })
public jobs?: string[];
}
const UserModel = getModelForClass(User); // UserModel is a regular Mongoose Model with correct types
(async () => {
await mongoose.connect('mongodb://localhost:27017/', { dbName: 'test' });
const { _id: id } = await UserModel.create({ name: 'JohnDoe', jobs: ['Cleaner'] });
const user = await UserModel.findById(id).exec();
console.log(user); // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 }
})();
A common problem when using Mongoose with TypeScript is that you have to define both the Mongoose model and the TypeScript interface. If the model changes, you also have to keep the TypeScript interface file in sync or the TypeScript interface would not represent the real data structure of the model.
Typegoose aims to solve this problem by defining only a TypeScript interface (class), which needs to be enhanced with special Typegoose decorators (like @prop
).
Under the hood it uses the Reflect & reflect-metadata API to retrieve the types of the properties, so redundancy can be significantly reduced.
Instead of writing this:
// This is a representation of how typegoose's compile output would look like
interface Car {
model?: string;
}
interface Job {
title?: string;
position?: string;
}
interface User {
name?: string;
age!: number;
preferences?: string[];
mainJob?: Job;
jobs?: Job[];
mainCar?: Car | string;
cars?: (Car | string)[];
}
const JobSchema = new mongoose.Schema({
title: String;
position: String;
});
const CarModel = mongoose.model('Car', {
model: string,
});
const UserModel = mongoose.model('User', {
name: { type: String },
age: { type: Number, required: true },
preferences: [{ type: String }],
mainJob: { type: JobSchema },
jobs: [{ type: JobSchema }],
mainCar: { type: Schema.Types.ObjectId, ref: 'Car' },
cars: [{ type: Schema.Types.ObjectId, ref: 'Car' }],
});
You can just write this:
class Job {
@prop()
public title?: string;
@prop()
public position?: string;
}
class Car {
@prop()
public model?: string;
}
class User {
@prop()
public name?: string;
@prop({ required: true })
public age!: number; // This is a single Primitive
@prop({ type: () => [String] })
public preferences?: string[]; // This is a Primitive Array
@prop()
public mainJob?: Job; // This is a single SubDocument
@prop({ type: () => Job })
public jobs?: Job[]; // This is a SubDocument Array
@prop({ ref: () => Car })
public mainCar?: Ref<Car>; // This is a single Reference
@prop({ ref: () => Car })
public cars?: Ref<Car>[]; // This is a Reference Array
}
yarn install
yarn run test
This Project should comply with Semver. It uses the Major.Minor.Fix
standard (or in NPM terms, Major.Minor.Patch
).
To ask questions or just talk with us, join our Discord Server.
+1
or similar comments to issues. Use the reactions instead.FAQs
Define Mongoose models using TypeScript classes
The npm package @typegoose/typegoose receives a total of 17,744 weekly downloads. As such, @typegoose/typegoose popularity was classified as popular.
We found that @typegoose/typegoose demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.