DEV Community

Code_Regina
Code_Regina

Posted on

|Database| Database: Connecting to Mongo with Mongoose

            -What is Mongoose 
-Schema Constraints
-Model Instance Methods
-Adding Model Static Methods
-Mongoose Virtual
-Defining Mongoose Middleware
Enter fullscreen mode Exit fullscreen mode




What is Mongoose

Object Data Mapper / Object Document Mapper

Mongoose is a ODM, which maps documents coming from a database into usable JavaScript objects.

Mongoose provides ways for us to model application data and define a schema. It offers an easy way to validate data and build complex queries from the comfort of JS.

It is also possible to define a preset schema ahead of time and then enforce it. Data will conform to that schema.

The goal of Mongoose is to take Mongo and make it work seamlessly better with JavaScript.

Schema Constraints

Schema types handle definitions of path defaults, validation, getters, setters, field selection defaults for queries.

Schema type is a configuration object for individual properties.

Schema types can be string, number, date, boolean, mixed, objectID, array, etc...

Schema type options

required, default, select, validate, get, set, immutable, and transform.

Model Instance Methods

Instances of models are documents. Documents have many of their own built-in instance methods.
An instance method is available on every single instance versus a class or static method.

Adding Model Static Methods

Static methods that live on the model itself, not on instances of the model.

Two ways to add a static method to the model

add a function property to schema.statics
call the Schema#static() function

Mongoose Virutals

Virtuals are document properties that can get and set but that do not get persisted to MongoDB. The getters are useful for formatting or combing fields, while setters are useful for de-composing a single value into multiple values for storage.

Defining Mongoose Middleware

Middleware are functions passed during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plug-ins.

Mongoose has 4 types of middleware: document, model, aggregate, and query,
The keyword this will refer to the document.

Common middle ware functions

Validate, save, remove, updateOne, deleteOne and init

Top comments (0)