npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@tsed/mongoose

v7.82.3

Published

Mongoose package for Ts.ED framework

Downloads

27,818

Readme

Build & Release PR Welcome npm version semantic-release code style: prettier github opencollective

A package of Ts.ED framework. See website: https://tsed.io/tutorials/mongoose.html

Features

Currently, @tsed/mongoose allows you:

  • Configure one or more MongoDB database connections via the @Configuration configuration. All databases will be initialized when the server starts during the server's OnInit phase.
  • Declare a Model from a class with annotation.
  • Declare inherited models in a single collection via @DiscriminatorKey.
  • Add a plugin, PreHook method and PostHook on your model.
  • Inject a Model to a Service, Controller, Middleware, etc...

Note: @tsed/mongoose use the JsonSchema and his decorators to generate the mongoose schema.

Installation

Before using the @tsed/mongoose package, we need to install the mongoose module.

npm install --save mongoose
npm install --save @tsed/mongoose
npm install --save-dev @types/mongoose

Then import @tsed/mongoose in your Server:

import {Configuration} from "@tsed/common";
import "@tsed/mongoose"; // import mongoose ts.ed module

@Configuration({
  mongoose: [
    {
      id: "default",
      url: "mongodb://127.0.0.1:27017/db1",
      connectionOptions: {}
    }
  ]
})
export class Server {}

Multi databases

The mongoose module of Ts.ED Mongoose allows to configure several basic connections to MongoDB. Here is an example configuration:

import {Configuration} from "@tsed/common";
import "@tsed/mongoose"; // import mongoose ts.ed module

@Configuration({
  mongoose: [
    {
      id: "default",
      url: "mongodb://127.0.0.1:27017/db1",
      connectionOptions: {}
    },
    {
      id: "default",
      url: "mongodb://127.0.0.1:27017/db2",
      connectionOptions: {}
    }
  ]
})
export class Server {}

MongooseService

MongooseService let you to retrieve an instance of Mongoose.Connection.

import {Service} from "@tsed/common";
import {MongooseService} from "@tsed/mongoose";

@Service()
export class MyService {
  constructor(mongooseService: MongooseService) {
    mongooseService.get(); // return the default instance of Mongoose.
    // If you have one or more database configured with Ts.ED
    mongooseService.get("default");
    mongooseService.get("db2");
  }
}

Declaring a Model

By default, Ts.ED mongoose will reuse the metadata stored by the decorators dedicated to describe a JsonSchema. This decorators come from the @tsed/common package.

Here a model example:

import {Minimum, Maximum, MaxLength, MinLength, Enum, Pattern, Required, CollectionOf} from "@tsed/common";
import {Model, Unique, Indexed, Ref, ObjectID} from "@tsed/mongoose";

enum Categories {
  CAT1 = "cat1",
  CAT2 = "cat2"
}

@Model({dbName: "default"}) // dbName is optional. By default dbName is equal to default
export class MyModel {
  @ObjectID()
  _id: string;

  @Unique()
  @Required()
  unique: string;

  @Indexed()
  @MinLength(3)
  @MaxLength(50)
  indexed: string;

  @Minimum(0)
  @Maximum(100)
  rate: Number;

  @Enum(Categories)
  // or @Enum("type1", "type2")
  category: Categories;

  @Pattern(/[a-z]/) // equivalent of match field in mongoose
  pattern: String;

  @CollectionOf(String)
  arrayOf: string[];

  @Ref(OtherModel)
  ref: Ref<OtherModel>;

  @Ref(OtherModel)
  refs: Ref<OtherModel>[];
}

Inject model

import {Service, Inject} from "@tsed/common";
import {MongooseModel} from "@tsed/mongoose";
import {MyModel} from "./models/MyModel.js";

@Service()
export class MyService {
  constructor(@Inject(MyModel) private model: MongooseModel<MyModel>): MyModel {
    console.log(model); // Mongoose.model class
  }

  async save(obj: MyModel): MongooseModel<MyModel> {
    const doc = new this.model(obj);
    await doc.save();

    return doc;
  }

  async find(query: any) {
    const list = await this.model.find(query).exec();

    console.log(list);

    return list;
  }
}

Register hook

Mongoose allows the developer to add pre and post hooks / middlewares to the schema. With this it is possible to add document transformations and observations before or after validation, save and more.

Ts.ED provide class decorator to register middlewares on the pre and post hook.

Pre hook

We can simply attach a @PreHook decorator to your model class and define the hook function like you normally would in Mongoose.

import {Required} from "@tsed/common";
import {PreHook, Model, ObjectID} from "@tsed/mongoose";

@Model()
@PreHook("save", (car: CarModel, next) => {
  if (car.model === "Tesla") {
    car.isFast = true;
  }
  next();
})
export class CarModel {
  @ObjectID()
  _id: string;

  @Required()
  model: string;

  @Required()
  isFast: boolean;

  // or Prehook on static method
  @PreHook("save")
  static preSave(car: CarModel, next) {
    if (car.model === "Tesla") {
      car.isFast = true;
    }
    next();
  }
}

This will execute the pre-save hook each time a CarModel document is saved.

Post hook

We can simply attach a @PostHook decorator to your model class and define the hook function like you normally would in Mongoose.

import {ObjectID, Required} from "@tsed/common";
import {PostHook, Model} from "@tsed/mongoose";

@Model()
@PostHook("save", (car: CarModel) => {
  if (car.topSpeedInKmH > 300) {
    console.log(car.model, "is fast!");
  }
})
export class CarModel {
  @ObjectID()
  _id: string;

  @Required()
  model: string;

  @Required()
  isFast: boolean;

  // or Prehook on static method
  @PostHook("save")
  static postSave(car: CarModel) {
    if (car.topSpeedInKmH > 300) {
      console.log(car.model, "is fast!");
    }
  }
}

This will execute the post-save hook each time a CarModel document is saved.

Plugin

Using the plugin decorator enables the developer to attach various Mongoose plugins to the schema. Just like the regular schema.plugin() call, the decorator accepts 1 or 2 parameters: the plugin itself, and an optional configuration object. Multiple plugin decorator can be used for a single model class.

import {Service} from "@tsed/common";
import {MongoosePlugin, Model, MongooseModel} from "@tsed/mongoose";
import * as findOrCreate from 'mongoose-findorcreate';

@Model()
@MongoosePlugin(findOrCreate)
class UserModel {
  // this isn't the complete method signature, just an example
  static findOrCreate(condition: InstanceType<User>):
    Promise<{ doc: InstanceType<User>, created: boolean }>;
}

@Service()
class UserService {
    constructor(@Inject(UserModel) userModel: MongooseModel<UserModel>) {
        userModel.findOrCreate({ ... }).then(findOrCreateResult => {
          ...
        });
    }
}

Discriminators

Set the @DiscriminatorKey decorator on a property in the parent class to define the name of the field for the discriminator value.

Extend the child model classes from the parent class. By default the value for the discriminator field is the class name but it can be overwritten via the discriminatorValue option on the model.

@Model()
class EventModel {
  @ObjectID()
  _id: string;

  @Required()
  time: Date = new Date();

  @DiscriminatorKey()
  type: string;
}

@Model()
class ClickedLinkEventModel extends EventModel {
  @Required()
  url: string;
}

@Model({discriminatorValue: "signUpEvent"})
class SignedUpEventModel extends EventModel {
  @Required()
  user: string;
}

For further information, please refer to the mongoose documentation about discriminators.

Contributors

Please read contributing guidelines here

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

The MIT License (MIT)

Copyright (c) 2016 - 2022 Romain Lenzotti

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.