Convert a typebox schema into a mongoose schema
npm i mongoose-typebox --save
yarn add mongoose-typebox
pnpm i mongoose-typebox
bun i mongoose-typebox
Or whatever we use these days
Some mongoose options are automatically inferred from typebox options :
typebox | mongoose |
---|---|
minLength | minlength |
maxLength | maxlength |
minimum | min |
maximum | max |
minByteLength | minlength |
All of them options are available in { mongoose: { ... } }
(these overwrites the ones above)
// Declare a typescript schema
const userTSchema = Type.Object({
username: Type.String({
minLength: 3,
maxLength: 20,
mongoose: { unique: true },
}),
password: Type.String({ minLength: 6 }),
firstName: Type.String(),
lastName: Type.String(),
middleName: Type.Optional(Type.String()),
});
// Convert it
const userSchema = typeboxToMongooseSchema(userTSchema);
// Use it
const userModel = mongoose.model("Users", userSchema);
const users = await userModel.find();
Anything you would've used as the second arg in new mongoose.Schema()
, you can use as the second arg of typeboxToMongooseSchema
⚠️ However, virtuals are not yet supported
const userSchema = typeboxToMongooseSchema(userTSchema, {
toJSON: {
transform: function (_doc, ret) {
delete ret.password;
},
},
methods: {
getFullName: function () {
return [this.firstName, this.middleName, this.lastName].filter(Boolean).join(" ");
},
},
statics: {
getByFirstName: function (firstName: string) {
return this.find({ firstName });
},
},
});
const userModel = makeMongooseModel("Users", userSchema);
Since mongoose.Model is a generic type, you must use the makeMongooseModel
helper function to keep statics and methods type-safety
Type.Union([Type.Literal("on"), Type.Literal("off")]);
or
enum Status {
On = "on",
Off = "off",
}
Type.Enum(Status),
Type.Uint8Array();
Type.Any();
Type.String({ ref: "Ref" });
or if the relation is 0,n
Type.Array(Type.String({ ref: "Ref" }));
Type.Number({ mongoose: { type: mongoose.Types.Decimal128 } });
Type.Number({ mongoose: { type: mongoose.Types.BigInt } });
Type.String({ mongoose: { type: mongoose.Types.UUID } });
This lib has been tested using mongoose ^7 and ^8, and typebox ^0.31.28