Skip to content

Convert Typebox object to Mongoose schema definition

Notifications You must be signed in to change notification settings

ledouxm/mongoose-typebox

 
 

Repository files navigation

mongoose-typebox

Convert a typebox schema into a mongoose schema

Installation

npm i mongoose-typebox --save
yarn add mongoose-typebox
pnpm i mongoose-typebox
bun i mongoose-typebox

Or whatever we use these days

Usage

Basic

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();

Extra data

Methods & Statics

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

How to get x mongoose types

Enum

Type.Union([Type.Literal("on"), Type.Literal("off")]);

or

enum Status {
    On = "on",
    Off = "off",
}

Type.Enum(Status),

Buffer

Type.Uint8Array();

Mixed

Type.Any();

ObjectId (Ref)

Type.String({ ref: "Ref" });

or if the relation is 0,n

Type.Array(Type.String({ ref: "Ref" }));

Decimal128

Type.Number({ mongoose: { type: mongoose.Types.Decimal128 } });

BigInt

Type.Number({ mongoose: { type: mongoose.Types.BigInt } });

UUID

Type.String({ mongoose: { type: mongoose.Types.UUID } });

Map

⚠️ Not supported

Versions

This lib has been tested using mongoose ^7 and ^8, and typebox ^0.31.28

About

Convert Typebox object to Mongoose schema definition

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 100.0%