0% found this document useful (0 votes)
79 views

Mongoose

This document provides an introduction and overview of Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js. It discusses how Mongoose manages relationships between data, provides schema validation, and translates between objects in code and their representation in MongoDB. Key concepts covered include collections, documents, fields, schemas, schema types, models, and basic CRUD operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Mongoose

This document provides an introduction and overview of Mongoose, an Object Data Modeling (ODM) library for MongoDB and Node.js. It discusses how Mongoose manages relationships between data, provides schema validation, and translates between objects in code and their representation in MongoDB. Key concepts covered include collections, documents, fields, schemas, schema types, models, and basic CRUD operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Desarrollo de Aplicaciones

Web
Daniel Sánchez Ruiz
Unidad Profesional Interdisciplinaria de Ingeniería campus Tlaxcala
Introduction to
Mongoose
Mongoose is an Object Data Modeling
(ODM) library for MongoDB and
Node.js.
It manages relationships between data,
provides schema validation, and is used
to translate between objects in code and
the representation of those objects in
MongoDB.
Introduction to Mongoose
MongoDB is a schema-less NoSQL document database. It means you
can store JSON documents in it, and the structure of these documents
can vary as it is not enforced like SQL databases.
This is one of the advantages of using NoSQL as it speeds up
application development and reduces the complexity of deployments.
Introduction to Mongoose
Introduction to Mongoose
• Collections. Collections in Mongo are equivalent to tables in relational databases. They can hold multiple JSON
documents.

• Documents. Documents are equivalent to records or rows of data in SQL. While a SQL row can reference data in
other tables, Mongo documents usually combine that in a document.

• Fields. Fields, also known as properties or attributes, are similar to columns in a SQL table. In the image above,
FirstName, LastName, Email, and Phone are all fields.

• Schema. While Mongo is schema-less, SQL defines a schema via the table definition. A Mongoose schema is a
document data structure (or shape of the document) that is enforced via the application layer.

• SchemaTypes. While Mongoose schemas define the overall structure or shape of a document, SchemaTypes define
the expected data type for individual fields (String, Number, Boolean, and so on).
Models
Models are higher-order constructors that take a schema and create an
instance of a document equivalent to records in a relational database.
Models
In the code above, puppySchema defines the shape of the document which has two fields, name,
and age.

The SchemaType for name is String and for age is Number. Note that you can define the
SchemaType for a field by using an object with a type property like with name. Or you can apply a
SchemaType directly to the field like with age.

Also, notice that the SchemaType for name has the option required set to true. To use options like
required and lowercase for a field, you need to use an object to set the SchemaType.

At the bottom of the snippet, puppySchema is compiled into a model named Puppy, which can then
be used to construct documents in an application.
Usage
npm install mongoose validator
Mongoose Schema vs. Model
A Mongoose model is a wrapper on the Mongoose schema.
A Mongoose schema defines the structure of the document, default
values, validators, etc., whereas a Mongoose model provides an
interface to the database for creating, querying, updating, deleting
records, etc.
Mongoose Schema vs. Model
Creating a Mongoose model comprises primarily of three parts:
• Referencing Mongoose. This reference will be the same as the one that
was returned when we connected to the database, which means the
schema and model definitions will not need to explicitly connect to the
database.
Mongoose Schema vs. Model
• Defining the Schema. A schema defines document properties through
an object where the key name corresponds to the property name in the
collection.

Here we define a property called email with a schema type String which
maps to an internal validator that will be triggered when the model is
saved to the database. It will fail if the data type of the value is not a
string type.
Mongoose Schema vs. Model
The following Schema Types are permitted:

• Array
• Boolean
• Buffer
• Date
• Mixed (A generic / flexible data type)
• Number
• ObjectId
• String
Mongoose Schema vs. Model
• Exporting a Model. We need to call the model constructor on the
Mongoose instance and pass it the name of the collection and a
reference to the schema definition.
Mongoose Schema vs. Model
Mongoose Schema vs. Model
A schema definition should be simple, but its complexity is usually
based on application requirements.
Schemas can be reused and they can contain several child-schemas too.
In the example above, the value of the email property is a simple value
type.
However, it can also be an object type with additional properties on it.
Mongoose Schema vs. Model
We can create an instance of the model we defined above and populate
it using the following syntax:
Mongoose Schema vs. Model
Let’s enhance the Email schema to make the email property a unique,
required field and convert the value to lowercase before saving it.
We can also add a validation function that will ensure that the value is a
valid email address. We will reference and use the validator library
installed earlier.
Mongoose Schema vs. Model
Basic Operations
Create Record
Let’s create an instance of the email model and save it to the database:
Basic Operations
Fetch Record
Let’s try to retrieve the record we saved to the database earlier. The
model class exposes several static and instance methods to perform
operations on the database.

We will now try to find the record that we created previously using the
find method and pass the email as the search term.
Basic Operations
Basic Operations
Update Record
Let’s modify the record above by changing the email address and
adding another field to it, all in a single operation.
For performance reasons, Mongoose won’t return the updated document
so we need to pass an additional parameter to ask for it:
Basic Operations
Basic Operations
Delete Record
Query Building
Mongoose has a very rich API that handles many complex operations supported by MongoDB.
Consider a query where we can incrementally build query components.

In this example, we are going to:

• Find all users


• Skip the first 100 records
• Limit the results to 10 records
• Sort the results by the firstName field
• Select the firstName
• Execute that query
Query Building
Vuex
Vuex is a state management pattern + library for Vue.js applications.
It serves as a centralized store for all the components in an application,
with rules ensuring that the state can only be mutated in a predictable
fashion.
What is a "State Management Pattern"?
What is a "State Management Pattern"?
It is a self-contained app with the following parts:

The state, the source of truth that drives our app;


The view, a declarative mapping of the state;
The actions, the possible ways the state could change in reaction to user
inputs from the view.
What is a "State Management Pattern"?
This is a simple representation of the concept of "one-way data flow":
What is a "State Management Pattern"?
However, the simplicity quickly breaks down when we have multiple components
that share a common state:

Multiple views may depend on the same piece of state.


Actions from different views may need to mutate the same piece of state.
For problem one, passing props can be tedious for deeply nested components, and
simply doesn't work for sibling components. For problem two, we often find
ourselves resorting to solutions such as reaching for direct parent/child instance
references or trying to mutate and synchronize multiple copies of the state via
events. Both of these patterns are brittle and quickly lead to unmaintainable code.
What is a "State Management Pattern"?
So why don't we extract the shared state out of the components, and
manage it in a global singleton? With this, our component tree becomes
a big "view", and any component can access the state or trigger actions,
no matter where they are in the tree!

By defining and separating the concepts involved in state management


and enforcing rules that maintain independence between views and
states, we give our code more structure and maintainability.
What is a "State Management Pattern"?
This is the basic idea behind Vuex, inspired by Flux, Redux and The
Elm Architecture.
Unlike the other patterns, Vuex is also a library implementation tailored
specifically for Vue.js to take advantage of its granular reactivity system
for efficient updates.
What is a "State Management Pattern"?
When Should I Use It?
Vuex helps us deal with shared state management with the cost of more concepts
and boilerplate. It's a trade-off between short term and long term productivity.

If you've never built a large-scale SPA and jump right into Vuex, it may feel
verbose and daunting. That's perfectly normal - if your app is simple, you will
most likely be fine without Vuex. A simple store pattern may be all you need.
But if you are building a medium-to-large-scale SPA, chances are you have run
into situations that make you think about how to better handle state outside of your
Vue components, and Vuex will be the natural next step for you.
State
Vuex uses a single state tree - that is, this single object contains all your
application level state and serves as the "single source of truth." This
also means usually you will have only one store for each application. A
single state tree makes it straightforward to locate a specific piece of
state, and allows us to easily take snapshots of the current app state for
debugging purposes.

The single state tree does not conflict with modularity - in later chapters
we will discuss how to split your state and mutations into sub modules.
State
Vuex uses a single state tree - that is, this single object contains all your
application level state and serves as the "single source of truth."
This also means usually you will have only one store for each
application.
A single state tree makes it straightforward to locate a specific piece of
state, and allows us to easily take snapshots of the current app state for
debugging purposes.
Mutations
The only way to actually change state in a Vuex store is by committing
a mutation. Vuex mutations are very similar to events: each mutation
has a string type and a handler.
The handler function is where we perform actual state modifications,
and it will receive the state as the first argument:
Mutations
You cannot directly call a mutation handler. Think of it more like event
registration: "When a mutation with type increment is triggered, call this
handler."
To invoke a mutation handler, you need to call store.commit with its
type:

You might also like