
Product
Introducing Socket Fix for Safe, Automated Dependency Upgrades
Automatically fix and test dependency updates with socket fix—a new CLI tool that turns CVE alerts into safe, automated upgrades.
mongoose-better-schemas
Advanced tools
Streamline TypeScript schema definitions, and add proper typings for select
and populate
projections.
The type definitions provided by mongoose are lacking in some of the most crucial areas: schema definition, select
, and populate
methods.
Consider the following limitations:
Schema types contain no information regarding the relationships between models: only ObjectId
is used to signify a reference to some model.
Therefore, these relationships must be specified manually on every single populate
call! This process quickly becomes unwieldy, all while being completely unchecked and prone to errors:
populate
.select
projections.
populate
method.The select
method has no effect on a query's return type: it assumes the full document is returned each time.
Therefore, you must manually write a type that represents the projection and assert it. This can quickly become complex when dealing with nested data or arrays, plus even more so when considering the intricacies of Mongo exclusive selects.
If any of these steps get botched, your typings will be incorrect without any warning, leading to bugs and/or runtime errors.
mongoose-better-schemas
solves all of the problems listed above with the following setup:
import mongoose from 'mongoose';
import { defineSchema, type DefineSchema } from 'mongoose-better-schemas';
// Define schema types
type TDriverSchema = DefineSchema<{
firstName: string;
lastName: string;
vehicles: TVehicleSchema[]; // defines a relationship
salary: number;
}>;
type TVehicleSchema = DefineSchema<{
make: string;
drivers: TDriverSchema[];
price: number;
}>;
// Construct mongoose Schemas
const DriverSchema = defineSchema<TDriverSchema>()({
firstName: String,
lastName: String,
vehicles: [{ ref: 'Vehicle', type: mongoose.Schema.Types.ObjectId }],
salary: Number,
});
const VehicleSchema = defineSchema<TVehicleSchema>()({
make: String,
drivers: [{ ref: 'Driver', type: mongoose.Schema.Types.ObjectId }],
price: Number,
});
// Register mongoose Models
const Driver = mongoose.model('Driver', DriverSchema);
const Vehicle = mongoose.model('Vehicle', VehicleSchema);
Now use the findProjected
and findOneProjected
methods on the models in your application code, instead of the untyped select
and populate
methods.
type QueryOptions = {
select?: { [path: string]: 0 | 1 }
populate?: { [path: string]: PopulateInfo | 1 }
lean?: boolean
skip?: number
limit?: number
sort?: { [path: string]: SortOrder }
};
type PopulateInfo = {
select?: { [path: string]: 0 | 1 }
populate?: { [path: string]: 1 | PopulateInfo } // deep-populate
nullable?: boolean // whether the lookup can yield a null or not
};
// `T` represents the fully transformed schema type (selected and populated)
Model.findProjected(filter: FilterQuery, opts: QueryOptions): Promise<T[]>;
Model.findOneProjected(filter: FilterQuery, opts: QueryOptions): Promise<T | null>;
defineSchema
method is due to function currying. This pattern is a workaround for a limitation with TypeScript, allowing us to partially infer generics: the schema type is passed manually, but the typings for custom query, instance, and static methods can be inferred automatically.FAQs
Streamline TypeScript schema definitions
The npm package mongoose-better-schemas receives a total of 4 weekly downloads. As such, mongoose-better-schemas popularity was classified as not popular.
We found that mongoose-better-schemas demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer 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.
Product
Automatically fix and test dependency updates with socket fix—a new CLI tool that turns CVE alerts into safe, automated upgrades.
Security News
CISA denies CVE funding issues amid backlash over a new CVE foundation formed by board members, raising concerns about transparency and program governance.
Product
We’re excited to announce a powerful new capability in Socket: historical data and enhanced analytics.