Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@noreajs/mongoose

Package Overview
Dependencies
Maintainers
1
Versions
55
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@noreajs/mongoose

Mongoose helpers

  • 0.0.9-1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5
increased by150%
Maintainers
1
Weekly downloads
 
Created
Source

NoreaJs Mongoose

NoreaJs Mongoose is a package which contains a set of tools intended to facilitate the use of mongoose.

Initial Features

  • MongoDB initialization
  • Model creation
  • Extraction of errors during validations

MongoDB initialization

To use MongoDB in your application, initialization is required. To do so with this little baby package, here's how:

Import the MongoDB context:

import { MongodbContext } from '@noreajs/mongoose';

Then use this line of code to initialize:

MongodbContext.init({
  connectionUrl: `MONGODB_CONNECTION_URL`,
  options: {}, // optional
  onConnect: () => {}, // optional
  onError: () => {} // optional
});

Model creation

Mongoose is the ideal tool when working with MongoDB. Very often to create a model, there is a set of information to take into account and the organization of the different elements constituting a model can become complicated. This package offers you a relatively simple way to proceed to create a model.

Full example of model declaration:

import { mongooseModel, Document, Schema } from "@noreajs/mongoose";

interface ITask extends Document {
  name: string;
  description?: string;
  createdAt: Date;
  updatedAt: Date;
}

export default mongooseModel<ITask>({
  name: "Task",
  collection: "tasks",
  schema: new Schema(
    {
      name: {
        type: Schema.Types.String,
        required: [true, "Task's name is required"],
      },
      description: {
        type: Schema.Types.String,
      },
    },
    {
      timestamps: true, // createdAt and UpdatedAt are created and managed by mongoose
    }
  ),
  autopopulate: true, // optional, default true
  paginate: true, // optional, default true
  aggregatePaginate: true, // optional, default true
  leanVirtuals: true, // optional, default true
  uniqueValidator: true,  // optional, default true
  plugins: (schema: Schema<any>) => {
      // add your mongoose plugin here
  },
  externalConfig: (schema: Schema<any>) => {
      // Define methods, virtuals and middlewares here
  },
});

The generic method used is mongooseModel.

The parameter of method mongooseModel is of the generic type MoongooseModelParams;

type MoongooseModelParams<T extends Document> = {
  name: string;
  collection?: string;
  skipInit?: boolean;
  paginate?: boolean;
  aggregatePaginate?: boolean;
  autopopulate?: boolean;
  leanVirtuals?: boolean;
  uniqueValidator?: boolean;
  uniqueValidatorMessage?: string;
  plugins?: (schema: Schema) => void;
  schema: Schema<T>;
  externalConfig?: (schema: Schema) => void;
}

MoongooseModelParams descriptions:

AttributeTypeOptionalDefaultDescription
namestringfalseModel name
collectionstringtrueCollection name (optional, induced from model name)
skipInitbooleantruefalseWhether to skip initialization or not
paginatebooleantruetrueThe plugin automatically added when true is Mongoose Paginate
aggregatePaginatebooleantruetrueThe plugin automatically added when true is Mongoose Aggregate Paginate V2
autopopulatebooleantruetrueAlways populate() certain fields in your Mongoose schemas. Only apply this plugin to top-level schemas. Don't apply this plugin to child schemas.
leanVirtualsbooleantruetrueAttach virtuals to the results of Mongoose queries when using .lean().
uniqueValidatorbooleantruetrueCatch unique validation error like normal validation error
uniqueValidatorMessagestringtrueExpected {PATH} to be unique.Unique validator message You can pass through a custom error message as part of the optional options argument: You have access to all of the standard Mongoose error message templating: :{PATH}, {VALUE}, {TYPE}
pluginsfunctiontrueAdd globaly a plugin to a mongoose schema
schemamongoose.SchematrueMongoose schema defining the model
externalConfigfunctiontrueConfigure the schema created by adding methods, middlewares, virtuals and many other things provided by Mongoose - Methods - https://mongoosejs.com/docs/guide.html#methods - Middlewares - https://mongoosejs.com/docs/middleware.html - Virtuals - https://mongoosejs.com/docs/guide.html#virtuals

Extraction of errors during validations

Linearize Mongoose errors when you catch them. The method used is linearizeErrors.

Mongoose validation errors normaly looks like this:

{
    "message": "Validation Error: First error, second error and many other (maybe) unnecessary",
    "errors": {
      "fieldA": {
        "message": "The field A is required",
        "...": "..."
      },
      "fieldB": {
        "message": "Th field B is not required (lol)",
        "...": "..."
      }
    }
}

While using linearizeErrors method, the error data become:

{
  "message": "This field A is required; Th field B is not required (lol)"
}

Example:

try {
    const task = new Task({
        name: 'Install it',
        description: ''
    })
    
    await task.save();
} catch (e) {
    // linearize here
    linearizeErrors(e);

    // or
    // linearizeErrors(e, {debug: true}); // to keep the original 'errors' attribute

    // return the response
    return res.status(500).json(e);
}

Todos

  • (more things will be added soon)

License

MIT

Keywords

FAQs

Package last updated on 24 May 2020

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc