KEMBAR78
Mongo DBPlus | PDF | Mongo Db | No Sql
0% found this document useful (0 votes)
57 views40 pages

Mongo DBPlus

This document provides an introduction to MongoDB, a NoSQL database that allows for flexible data storage using JSON-like documents. It covers installation, database management, collection management, and CRUD operations, highlighting the advantages of MongoDB over traditional relational databases like MySQL. The document also includes quizzes and assessments to reinforce learning about MongoDB's features and functionalities.

Uploaded by

Wissem Chehaider
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views40 pages

Mongo DBPlus

This document provides an introduction to MongoDB, a NoSQL database that allows for flexible data storage using JSON-like documents. It covers installation, database management, collection management, and CRUD operations, highlighting the advantages of MongoDB over traditional relational databases like MySQL. The document also includes quizzes and assessments to reinforce learning about MongoDB's features and functionalities.

Uploaded by

Wissem Chehaider
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

MongoDB (CRUD)

MongoDB (CRUD) Introduction


MongoDB Definition
Congrats! You have made it this far!
After we have created the server using Express.js, we are going to learn how to store
the data. To do that, we are going to use the famous MongoDB.

In the following chapter, we are going to learn:


How to install MongoDB.
How to manage our database.
The best ways to create, query, update and delete documents in MongoDB.

MongoDB Definition
MongoDB is an object-oriented, simple, dynamic and
scalable NoSQL database. It is based on the NoSQL document storage
model where the data objects are stored as separate and flexible JSON-
like documents. The data objects are stored in a collection instead of
columns and rows like a traditional relational database. This means that
the fields can differ from one document to another and data structure can
be changed over time.
The goal and purpose of MongoDB is to offer a data store that has high-
performance, high-availability and horizontal scaling. MongoDB is easy to
install and free to use.
Versions released prior to October 16, 2018, are published under the AGPL
and its general distributions support Windows, Linux, Mac OS X, and
Solaris.
Why is using MongoDB better than
using MySQL? 🤔
Organizations of all sizes are choosing MongoDB because it helps them
build applications faster and handle multiple different types of data. It also
assists them in managing applications more efficiently depending on the
size of the project.

Development is now simplified with MongoDB. That is because MongoDB


documents map and integrate naturally with modern and object-oriented
programming languages.

Using MongoDB can remove the complex object-relational mapping (ORM)


layer that translates objects in code to relational tables. Added to that,
MongoDB’s flexible data model means that your database can evolve and
meet business requirements.

MySQL’s rigid and inflexible relational structure adds overhead to


applications and slows developers down as they must adapt objects in
code to relational structure.

Some keywords before we start


During this course, we are going to use some technical terms. So it’s best
if we define them before we start:
Schema: A database schema is the skeleton structure that represents the
logical view of the entire database. It defines how the data is organized
and how the relations among them are associated. It formulates all the
rules that are to be applied on the data. It is like a blueprint or a roadmap
that guides the user..
Document: the document is the unit that is stored in the MongoDB
database. Document uses JSON (JavaScript Object Notation, is a
lightweight, thoroughly explorable format used to exchange data between
various applications) data format. We can think of it like a row in an excel
sheet.
Collection : a collection is where the documents are stored. We can
compare it to the excel sheet that contains many rows.

Key Advantages of Using MongoDB


Schema less − MongoDB is a document database in which one collection
holds different documents. The number of fields, content and size of the
document can differ from one document to another. Optionally, schema
validation can be used to apply data governance controls over each
collection.
Deep query-ability. MongoDB supports dynamic queries on documents
using a document-based query language that is called MongoDB Query
Language (MQL). It is nearly as powerful as SQL.
Higher Availability − MongoDB automatically replicates your data to
additional nodes for high availability and security. In the event of a system
failure, the procedure of failover completes automatically - typically in less
than 5 seconds.
Faster Development: MongoDB’s document data model maps naturally
to objects in application code, making it simple for developers to learn and
use.
Scale Infinitely and Cheaply (Ease of scale-out) − MongoDB includes
native support for distributing or sharding a database across any number
of commodity machines in a way that is clear to the application.

Assessment: Quiz
MongoDB is generally used at the _________________.

Frontend Backend Middleware All of the above.


Which one of the following is correct?

MongoDB is column oriented data store. None of the above. MongoDB is a


NoSQL database. MongoDB uses XML instead of JSON for storing documents.
MongoDB is an X-based database?

All of the choices below. Key / Value Document Graph


What is supported by MongoDB?

SQL XML BSON None of the above.

Install MongoDB
Installation ⚙️
MongoDB is available in two server editions: Community and Enterprise.
MongoDB Enterprise provides various features that not available in the
MongoDB Community edition, such as In-Memory Storage Engine,
Auditing, Kerberos Authentication…

For learning purposes, MongoDB Community edition meets our


requirements a lot more than its different counterpart. That's why in this
section, we will cover the installation on both Windows and Linux (Ubuntu)
operating systems. If you have a different OS, you can refer to the official
documentation where you can find tutorials for all supported distributions.

Windows ½
 Windows installation
To install MongoDB on windows OS, you only have to visit the link and
follow the instructions. For Windows 7 and older, you should remove the
check button on the mongo compass and install it separately)

 Linux Installation:
See at this YouTube link : https://www.youtube.com/watch?v=d4jPEfky3L8

Assessment: Quiz
To install MongoDB, we need a special operating system.

True False
To verify MongoDB's version, we use the command:

mongo --version mongo -v Mongodb --version


Mongo shell is the interface used to manipulate MongoDB through the terminal.

True False

Database Management
Database Management 🕹️
db.getName()
Returns: the current database name.
db.version()
Returns: The mongod version or mongos instance.
db.stats(scale)
The db.stats() method returns a document with statistics reflecting the
database system’s state.
The scale is used on various data sizes. The scale defaults to 1 in order to
return data sizes in bytes. To display sizes in kilobytes instead of bytes,
specify a scale value of 1024.

Look at this Youtube link : https://www.youtube.com/watch?


v=QP6mghENS_U

Database Management 🕹️
Here is some other database methods:

 db.getName(): Returns the current database name.


 db.version(): Returns the mongod version or mongos instance.
 db.stats(scale): The db.stats() method returns a document with
statistics reflecting the database system’s state
o The scale defaults to 1 in order to return data sizes in bytes.
To display sizes in kilobytes instead of bytes, specify a scale
value of 1024.

Database Management 🕹️
 db.serverStatus(): Returns a document that provides an overview
of the database process’ state.

db.serverStatus( { repl: 0, metrics: 0, locks: 0 } )

 db.hostInfo(): Returns a document with information about the


underlying system that the mongod or mongos runs on.

 db.cloneDatabase("hostname"): Copies a remote database to


the current database. The command assumes that the remote
database has the same name as the current database.
hostname strings the hostname of the database to copy.

 db.copyDatabase(): Copies a database either from one mongod


instance to a current mongod instance, or it copies it within the
current mongod.

Assessment: Quiz
Which of these can provide an insight on MongoDB database process’s state?

locks.deadlockCoun globalstats serverStatus


What command will you use to show the current database's name?

db.getName() db.name() getName() db


To switch from one database to another, which command do we use?

Switch <db_Name> Change <db_Name> Use <db_Name>

Collection Management
Collection Management 🕹️
Now after we have learned how to manipulate a database, it’s
time to manipulate the collections of our database:
P.S. The methods listed on this table of contents page refer to the mongo
shell methods, and not to the MongoDB Node.js driver (or any other
driver) methods.

 db.createCollection(): Because MongoDB creates a collection implicitly


when the collection is first referenced in a command, this method is used
primarily for creating new collections that use specific options. For
example, you use db.createCollection() to create a capped collection, or to
create a new collection that uses document validation.
 db.collection.count(): Returns the documents count that would match a
find() query for the collection or view. The db.collection.count() method
does not perform the find() operation but instead counts and returns the
number of results that match a query.

Collection Management 🕹️
 db.collection.stats(): Reports a collection's state.
 db.collection.storageSize(): Reports the total storage size used
by the collection in bytes.
 db.collection.validate(<option>): Validates a collection. The
method scans a collection data and indexes for correctness and
returns the result.
o full: Optional. A flag that determines whether the command
performs a slower but more thorough check, or a faster but
less thorough check.

db.collection.validate( {

full: <boolean> // Optional

} )
db.collection.validate( <boolean> ) // full option

Collection Management 🕹️
db.collection.explain(verbosity)
Returns information on the query plan for the following methods:

 aggregate()
 count()
 find()
 remove()
 update()
 distinct()
 findAndModify()
Verbosity: Optional. Specifies the verbosity mode for the explain output.
The mode affects the behavior of explain() and determines the amount of
information to return. The possible modes are:

 "queryPlanner" (Default)
 "executionStats"
 "allPlansExecution"
db.products.explain("allPlansExecution").update( { $set: { reorder: true
} })

Assessment: Quiz
Which one is not a verbosity mode in the explain method?

“queryPlanner" "executionStats" "anyPlansExecution"


What command will you use to show the total storage used by the collection?

db.collection.printSize() db.collection.size db.collection.getTotalSize()


db.collection.storageSize()
Which of the following methods can provide the collection documents count?

db.collection.count db.collection.length db.collection.totalCount


CRUD Operations
CRUD operations
When we are dealing with databases, there are four operation that we can
apply:

 CREATE: or insert operations add new documents to a collection. If


the collection does not currently exist, insert operations will create a
new collection.
 READ: operations retrieve documents from a collection; i.e. queries.
 UPDATE: operations modify existing documents in a collection.
 DELETE: operations remove documents from a collection

The four first letters of each word makes up the CRUD acronym.

Fill in the blanks Solution


In computer programming, create , read, update, and delete (CRUD) are the four
basic functions of storage. Alternate words are sometimes used when defining the
four basic functions of CRUD, such as query instead of read, modify instead of
update, or destroy instead of delete.

Create Document
Create Document 📄
MongoDB provides the following methods to insert documents into a
collection:
 db.collection.insert()
 db.collection.insertOne()
 db.collection.insertMany()
 db.collection.save()
Look at this YouTube link : https://www.youtube.com/watch?
v=Br0K85I7DXw

Insert Document 📄
db.collection.insertOne()

Inserts a document into a collection.


db.collection.insertOne(

<document>,

writeConcern: <document>

 document: The document to be saved to the collection.


 writeConcern: Write concern describes the level of acknowledgment
requested from MongoDB for write operations.

Insert Document 📄
db.collection.save()
It updates an existing document or inserts a new document depending on
the parameter.
The save() method uses either the insert or the update command, which
uses the default write concern. To specify a different write concern,
include the write concern in the options parameter.
db.collection.save(

<document>,

writeConcern: <document>

)
db.products.save( { item: "book", qty: 40 } )

 document: document to save to the collection.


 writeConcern: Write concern describes the level of acknowledgment
requested from MongoDB for write operations

Note: MongoDB deprecates the db.collection.save() method. Instead use


db.collection.insertOne() or db.collection.replaceOne() instead.

Assessment: Quiz
db.collection.save() is still a valid method for mongodb.

True False
MongoDB provides the following methods to insert documents into a collection:
db.collection.insert() db.collection.insertOne() db.collection.insertMany()

True False
Which one of the following operations adds a new document to the users' collection?

add insert truncate drop

Query Documents
Query Documents 🔍
Look at this Youtube link: https://www.youtube.com/watch?
v=Gv5GxcKKRSE

Assessment: Quiz
Which one of the following methods is used to query documents in collections?

find move shell replace


Choose the correct statement.

Queries specify criteria, or conditions, that identify the documents that MongoDB
returns to the clients Write operations, or queries, retrieve data stored in the
database. The selection limits the amount of data that MongoDB returns to the
client over the network All of the above.
What will be the output?

db.products.find( { price : { $gt : 18 }, reviews : { $gt : 400 } } );


products with price greater than 18 and reviews greater than 400 products
reviews greater than 400 Will return syntax error products with price greater
than or equal to 18 or greater than to 400
Which one of the following methods returns one document?

findOne() findOne1() selectOne() all of the mentioned

Update Document
Update Document 📄
db.collection.save()
Updates an existing document or inserts a new document depending on
the document's parameter.
The save() method uses either the insert or the update command, which
uses the default write concern. To specify a different write concern,
include the write concern in the options parameter.
db.collection.save(

<document>,

writeConcern: <document>

db.products.save( { item: "book", qty: 40 } )

 document: the document to be saved to the collection.


 writeConcern: Write concern describes the level of acknowledgment
requested from MongoDB for write operations

Note: MongoDB rejects the db.collection.save() method. Instead use


db.collection.insertOne() or db.collection.replaceOne() instead.

Update Document 📄
Look at this YouTube link: https://www.youtube.com/watch?
v=iIugpCh54BA

Assessment: Quiz
What does the following query do when performed on the posts collection?
1
db.posts.update({ _id: 1 }, { $set: { Author: "Tom" } })

Sets the complete document with _id as 1 with the document specified in second parameter
by replacing it completely Adds a new field Author in the searched collection if not already
present Updates only the Author field of the document with _id as 1

Rewrite the following query using another mongoDB method.

db.posts.update({ _id: 1 }, { $set: { Author: "Tom" } })

db.posts.findOneAndUpdate({ _id:1 },{ $set: { Author: “Tom" } })


db.posts.updateOne({ _id:1 },{ $set: { Author: “Tom" } })
The .save() method can be used to insert and update documents.

True False

Delete Documents 🗑️
Look at this Youtube Link:
https://www.youtube.com/watch?v=NtvtFtEcCQQ

Assessment: Quiz
Which one of the following operations removes a document from MongoDB
collection?

deleteOne clear truncate drop


List the method that deletes one mongo document.

deleteOne() findOneAndDelete()
Which one of the following commands removes a single document that matches the
condition of the author’s name being John?

db.authors.deleteOne({ name: “John” }) db.authors.deleteMany({ name:


“John” }) db.authors.delete({ name: “John” })
Conclusion
MongoDB (CRUD) RECAP
Congratulation! By now we have learned one of the most important parts
of developing web applications which is storing data. During this super
skill, we have understood how we can store and manipulate data in a
MongoDB database. However, there's still more to learn. The next step is
to learn how to make our web application communicate with the database.

Mongoose

Mongoose Introduction
What's mongoose?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and
Node.JS. It is responsible for:

 Managing data relationships.


 Providing schema validation.
 Implementing the translation between code objects and the
representation of those objects in MongoDB.
Mongodb vs SQL
You know by now that MongoDB is a schema-less NoSQL document
database. It means you can store JSON documents on it. 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.

The example below is a reminder of how data is stored in Mongo vs. SQL
Database:
Fill in the blanks Solution
Mongoose is a MongoDB object modeling tool or ODM (Object Document Mapper). It's
written in JavaScript and designed to work in an asynchronous environment.

Terminologies
Just as a reminder, here are some terminologies used with the NoSQL
database:

 Collections: Collections in Mongo are the equivalent of tables in


relational databases. They can hold multiple JSON documents.
 Documents: Documents are the equivalent of records or data rows
in SQL. While an SQL row can reference data in other tables, Mongo
documents usually combine them in one document.
 Fields: Fields or attributes that are similar to columns in an SQL
table.
 Schema: While Mongo is schema-less, SQL defines a schema via the
table definition. A Mongoose ‘schema’ is a document data structure
(or a shape of the document) that is enforced via the application
layer.
 Models: Models are higher-order constructors that take a schema
and create an instance of a document equivalent to records in a
relational database.
 References: References are referred from one document to another
using the value of the referenced (parent) document.
Fill in the blanks Solution
Fields or attributes are similar to columns in an SQL table. Collections in Mongo are
equivalent to tables in relational databases. They can hold multiple JSON documents.
A Mongoose Schema is a document data structure (or a shape of the document) that
is enforced via the application layer. Models are higher-order constructors that take a
schema and create an instance of a document that is equivalent to records in a
relational database. Documents are equivalent to records or data rows in SQL. While
an SQL row can reference data in other tables, Mongo documents usually combine
them in a document.

Getting Started
Getting Started
1. Mongo Installation: First, we need MongoDB to be installed in our
machine (check the MongoDB Super Skill if needed)

Let’s have a look at some of the basics of Mongoose by implementing a


model that presents the data of a simplified address book.

Fire up your favorite IDE (ahem..VSCode), create a blank project, and let’s
get started! We will be using the limited ES6 syntax in Node, (so we won’t
be configuring Babel).

2. Mongoose Installation
Let’s go to the project folder and initialize our project:

npm init -y

Let’s install Mongoose and a validation library with the following


command:
npm install mongoose validator
The above install command will install the latest version of the
libraries. The Mongoose syntax in this course is specific to Mongoose v5
and beyond.

3. Database Connection
Create a file ./src/database.js under the project's root.
Next, we will add a simple class with a method that connects to the
database.
Your connection string will vary based on your installation.

let mongoose = require('mongoose');

const server = '127.0.0.1:27017'; // REPLACE WITH YOUR DB SERVER

const database = 'myDB'; // REPLACE WITH YOUR DB NAME

class Database {

constructor() {

this._connect()

_connect() {

mongoose.connect(`mongodb://${server}/${database}`)

.then(() => {

console.log('Database connection successful')

})

.catch(err => {

console.error('Database connection error')

})

module.exports = new Database()

The require(‘mongoose’) call above returns a Singleton object. It means that


when you call require(‘mongoose’) for the first time, it creates an instance
of the Mongoose class and returns it. On subsequent calls, it will return the
same instance that was created and returned to you the first time because
of how module import/export works in ES6.

Side Note
About Module import/require work-flow:

In the previous code, we have also turned our database class into a singleton by
returning an instance of the class in the module.exports statement because we
only need a single connection to the database.
ES6 makes it very easy for us to create a singleton (single instance) pattern
because of how the module loader works by caching the response of a previously
imported file.

Solution
Reorder the following function:
function connect() {

mongoose.connect(`mongodb://${server}/${database}`)

.then(() => {

console.log('Database connection successful') })

.catch(err => {

console.error('Database connection error') })

}}

Mongoose Schema vs. Model


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.

Creating a Mongoose model comprises primarily of three parts:

1. Referencing Mongoose
let mongoose = require('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.

2. Defining the Schema


A schema defines document properties through an object where the key
name corresponds to the property name in the collection.
let emailSchema = new mongoose.Schema({

email: String

})

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.
The following Schema Types are permitted:

 Array
 Boolean
 Buffer
 Date
 Mixed (A generic / flexible data type)
 Number
 ObjectId
 String

Mixed and ObjectId are defined under require(‘mongoose’).Schema.Types.

3. 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.
module.exports = mongoose.model('Email', emailSchema)

Let’s combine the code above into ./src/models/email.js to define the


contents of a basic email model:
let mongoose = require('mongoose')
let emailSchema = new mongoose.Schema({

email: String

})

module.exports = mongoose.model('Email', emailSchema)

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.

We can also create an instance of the model we've defined above and
populate it using the following syntax:
let EmailModel = require('./email')

let msg = new EmailModel({

email: 'ada.lovelace@gmail.com'

})

Let’s enhance the email schema to make the email property a unique and
required field. We can then 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.
let mongoose = require('mongoose')

let validator = require('validator')

let emailSchema = new mongoose.Schema({

email: {

type: String,

required: true,

unique: true,

lowercase: true,

validate: (value) => {

return validator.isEmail(value)

}
})

module.exports = mongoose.model('Email', emailSchema)

Assessment: Quiz
What are the permitted Schema Types in Mongoose?

Array Boolean Buffer Date Mixed Number ObjectId String


A Mongoose model is a wrapper on the Mongoose schema.

True False
A schema defines document properties.

True False

Basic Operations
Mongoose has a flexible API and provides many ways to accomplish a task.
We will not focus on the variations because that is out of the scope of this
course. However, try to remember that most of the operations can be
done in more than one way either syntactically or via the application's
architecture.

Create Record
Let’s create an instance of the email model and save it to the database:
let EmailModel = require('./email')

let msg = new EmailModel({

email: 'ADA.LOVELACE@GMAIL.COM'

})

msg.save()

.then(doc => {

console.log(doc)

})

.catch(err => {

console.error(err)

})

The result is a document that is returned upon a successful save:


{

_id: 5a78fe3e2f44ba8f85a2409a,

email: 'ada.lovelace@gmail.com',

__v: 0

The following fields are returned (internal fields are prefixed with an
underscore):

1. The _id field is auto-generated by Mongo and is a primary key of the


collection. Its value is a unique identifier for the document.
2. The value of the email field is returned. Notice that it is lower-case
because we specified the lowercase:true attribute in the schema.
3. __v is the versionKey property set on each document when first created
by Mongoose. Its value contains the internal revision of the document.

If you try to repeat the save operation above, you will get an error
because we have specified that the email field should be unique.
311790:0

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
have created previously using the find method and pass the email as the
search term.
EmailModel

.find({

email: 'ada.lovelace@gmail.com' // search query

})

.then(doc => {

console.log(doc)

})

.catch(err => {

console.error(err)

})

The document returned will be similar to what was displayed when we


created the record:
{

_id: 5a78fe3e2f44ba8f85a2409a,

email: 'ada.lovelace@gmail.com',

__v: 0

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:
EmailModel

.findOneAndUpdate(

email: 'ada.lovelace@gmail.com' // search query

},

email: 'theoutlander@live.com' // field:values to update

},

new: true, // return updated doc

runValidators: true // validate before update

})

.then(doc => {

console.log(doc)

})

.catch(err => {

console.error(err)

})

The document returned will contain the updated email:


{

_id: 5a78fe3e2f44ba8f85a2409a,

email: 'theoutlander@live.com',

__v: 0

Delete Record
We will use the findOneAndRemove call to delete a record. It returns the
original document that was removed:
EmailModel

.findOneAndRemove({

email: 'theoutlander@live.com'

})

.then(response => {

console.log(response)

})

.catch(err => {

console.error(err)

})

Fill in the blanks Solution


How to add records in a document with the model? var userDetails
= newUser({ name: 'Test
user',username:'testuser',password:'test12@',location:'mohali' });
userDetails. save (function (err) {if (err) console.log ('Error on save!')});

Helpers.
Helpers
So far, we have looked at some of the basic functionalities known as CRUD
(Create, Read, Update, Delete) operations, but Mongoose also provides the
ability to configure several types of helper methods and properties. These
can be used to further simplify working with data.
Let’s create a user schema in ./src/models/user.js with the
fields firstName and lastName:
let mongoose = require('mongoose')

let userSchema = new mongoose.Schema({

firstName: String,

lastName: String

})

module.exports = mongoose.model('User', userSchema)

Virtual Property
A virtual property is not restricted the database. We can add it to our
schema as a helper to get and set values.
Let’s create a virtual property called fullName which can be used to set
values on firstName and lastName and retrieve them as a combined value
when read:
userSchema.virtual('fullName').get(function() {

return this.firstName + ' ' + this.lastName

})

userSchema.virtual('fullName').set(function(name) {

let str = name.split(' ')

this.firstName = str[0]

this.lastName = str[1]

})

Callbacks for get and set must use the function keyword as we need to
access the model via the this keyword. Using fat arrow functions will
change what this refers to.

Now, we can set firstName and lastName by assigning a value to fullName:


let model = new UserModel()

model.fullName = 'Thomas Anderson'

console.log(model.toJSON()) // Output model fields as JSON

console.log()
console.log(model.fullName) // Output the full name

The code above will output the following:


{ _id: 5a7a4248550ebb9fafd898cf,

firstName: 'Thomas',

lastName: 'Anderson' }

Thomas Anderson

Instance Methods
We can create custom helper methods on the schema and access them
via the model instance. These methods will have access to the model
object and they can be used quite creatively. For instance, we could create
a method to find all the people who have the same first name as the
current instance.
In this example, let’s create a function to return the initials for the current
user. Let’s add a custom helper method called getInitials to the schema:
userSchema.methods.getInitials = function() {

return this.firstName[0] + this.lastName[0]

This method will be accessible via a model instance:


let model = new UserModel({

firstName: 'Thomas',

lastName: 'Anderson'

})

let initials = model.getInitials()

console.log(initials) // This will output: TA

Static Methods
Similar to instance methods, we can create static methods on the schema.
Let’s create a method to retrieve all users in the database:
userSchema.statics.getUsers = function() {

return new Promise((resolve, reject) => {

this.find((err, docs) => {

if(err) {
console.error(err)

return reject(err)

resolve(docs)

})

})

Calling getUsers on the Model class will return all the users in the database:
UserModel.getUsers()

.then(docs => {

console.log(docs)

})

.catch(err => {

console.error(err)

})

Adding instance and static methods is a nice approach to implement an


interface to database interactions on collections and records.

Middleware
Middleware is a set of functions that run at specific stages of a pipeline.
Mongoose supports middleware for the following operations:

 Aggregate
 Document
 Model
 Query

For instance, models have pre and post functions that take two
parameters:

1. Type of event (‘init’, ‘validate’, ‘save’, ‘remove’)


2. A callback that is executed with this referencing the model instance

Example of Middleware (a.k.a. pre and post hooks):


Middleware
Let’s demonstrate this, as an example, by adding two fields
called createdAt and updatedAt to our schema:
let mongoose = require('mongoose')

let userSchema = new mongoose.Schema({

firstName: String,

lastName: String,

createdAt: Date,

updatedAt: Date

})

module.exports = mongoose.model('User', userSchema)

When model.save() is called, there is a pre(‘save’, …) and post(‘save’,


…) event that is triggered. For the second parameter, you can pass a
function that is called when the event is triggered. These functions take a
parameter to the next function in the middleware chain.

Let’s add a pre-save hook and set values for createdAt and updatedAt:
userSchema.pre('save', function (next) {

let now = Date.now()

this.updatedAt = now

// Set a value for createdAt only if it is null

if (!this.createdAt) {

this.createdAt = now

}
// Call the next function in the pre-save chain

next()

})

Let’s create and save our model:


let UserModel = require('./user')

let model = new UserModel({

fullName: 'Thomas Anderson'

msg.save()

.then(doc => {

console.log(doc)

})

.catch(err => {

console.error(err)

})

You should see values for createdAt and updatedAt when the created record
is printed:
{ _id: 5a7bbbeebc3b49cb919da675,

firstName: 'Thomas',

lastName: 'Anderson',

updatedAt: 2018-02-08T02:54:38.888Z,

createdAt: 2018-02-08T02:54:38.888Z,

__v: 0 }

Plugins
Suppose that we want to track when a record was created and last
updated on every collection in our database. Instead of repeating the
above process, we can create a plugin and apply it to every schema.

Let’s create a file ./src/model/plugins/timestamp.js and replicate the above


functionality as a reusable module:
module.exports = function timestamp(schema) {
// Add the two fields to the schema

schema.add({

createdAt: Date,

updatedAt: Date

})

// Create a pre-save hook

schema.pre('save', function (next) {

let now = Date.now()

this.updatedAt = now

// Set a value for createdAt only if it is null

if (!this.createdAt) {

this.createdAt = now

// Call the next function in the pre-save chain

next()

})

To use this plugin, we simply pass it to the schemas that should be given
this functionality:
let timestampPlugin = require('./plugins/timestamp')

emailSchema.plugin(timestampPlugin)

userSchema.plugin(timestampPlugin)

Assessment: Quiz
Helpers are functions provided by Mongoose.

True False
Virtual properties are only restricted to the database.

true false
In which operations does Mongoose support middleware?

Aggregate Document Model Query

Query Building
Query Building
Mongoose has a very rich API that handles many complex operations
supported by MongoDB. Let's take for example a query where we can
incrementally build query components.

In this example, we are going to:

1. Find all users.


2. Skip the first 100 records.
3. Limit the results to 10 records.
4. Sort the results by the firstName field.
5. Select the firstName.
6. Execute that query.

UserModel.find() // find all users

.skip(100) // skip the first 100 items

.limit(10) // limit to 10 items

.sort({firstName: 1} // sort ascending by firstName

.select({firstName: true} // select firstName only

.exec() // execute the query

.then(docs => {

console.log(docs)

})

.catch(err => {

console.error(err)

})

Fill in the blanks Solution


Comment on the following code: ```javascript var queryChain = function(done) { var
foodToSearch = "burrito"; Person // find all people who love
burritos.find({favoriteFoods:foodToSearch}) // sort results by name in ascending
order.sort({name : "asc"}) // pick the first 2 records.limit(2) // hide the ages.select("-
age") // execute the query.exec((err, data) => { if(err) done(err); done(null,
data); }) }; ```

Conclusion
Mongoose RECAP
We have covered the basics Mongoose and what it can do. It is a rich
library full of useful and powerful features that make it a joy to work with
data models in the application layer.

While you can interact with Mongo directly using Mongo Driver, Mongoose
will simplify that interaction by allowing you to model relationships
between data and validate them easily.

Fun Fact: Valeri Karpov the creator of mongoose was the one who coined
the term The MEAN Stack.

REST API
REST API Introduction
Introduction
What is a REST API ?
Let’s say you’re trying to find Batman videos on Youtube. You open up
Youtube, type “Batman” into the search field, hit enter, and you see a list
of videos about Batman. A REST API works in a similar way. You search for
something and you get a list of results back from the service you’re
requesting it from.

API: Application Programming Interface


It is a set of rules that allows programs to talk to each other. The
developer creates the API on the server and allows the client to talk to it.

REST: REpresentational State Transfer


Determines how the API looks like. It is a set of rules that developers follow
when they create their API. One of these rules states that you should be
able to get a piece of data (called a resource) when you link to a specific
URL.
Assessment: Quiz
What does REST stand for ?

REpresentational State Transfer REpublish State Transfer REpresentational


State Transition
RESTful is a set of recommendations.

True False
RESTful API is only an API that is created under Node.js

True False

Request
The internet boasts a vast array of resources hosted on different servers.
For you to access these resources, your browser needs to be able to send
a request to the servers and display the resources for you. HTTP
(Hypertext Transfer Protocol) is the underlying format that is used to
structure requests and responses for effective client-server
communication. The message that is sent by a client to a server is what is
known as an HTTP request. Clients can use various methods to send
requests to a server.

Therefore, HTTP request methods are the assets that indicate the specific
desired action to be performed on a given resource. Each method
implements a distinct semantic, but there are some standard features that
are shared by the various HTTP request methods.

To test HTTP requests, we can use softwares like Postman

Assessment: Quiz
The request is sent from the browser to a server.

True False
The request is sent via the SMTP protocol.

True False
The HTTP request can only have one type of method.

True False

Request Headers
Headers are used to provide information to both the client and the server.
It can be used for many purposes, such as authentication and providing
information about the body content.

Example of a HTTP Request Headers:

Assessment: Quiz
Request headers are used to hold messages.

True False
Request headers provide information to servers and clients.

True False
The request header holds only the authentication information.

True False

Request Body
The body (sometimes called “data” or “message”) contains information
you want to be sent to the server. This option is only used with POST, PUT
or DELETE requests.

For a sign in request, a body example can be the email and password.
Assessment: Quiz
The request body can also be called

Data Message Statement


The request body is used with the get method

True False
The request body contains the result of the request.

True False

Response
HTTP Response
When a client (browser) makes a request to a server, the server responds
with a reply including a status code.

HTTP response status codes indicate whether a specific HTTP request has
been successfully completed. Responses are grouped in five classes:

Informational responses (100–199),


Successful responses (200–299),
Redirects (300–399),
Client errors (400–499),
and Server errors (500–599).
Assessment: Quiz
The response of a successful POST 127.0.0.1:30001/product/create request will have
a status code equal to?

101 201 301 401 501


The response status varies between 100 and 599.

True False
The response is sent from the client to the server.

True False

Post (REST API)


POST Method
This request is used to create a new resource on a server. If you perform
a POST request, the server creates a new entry in the database and tells
you whether the creation is successful or not. In other words,
a POST request performs an CREATE operation.

Fill in the blanks Solution


We use POST requests to make CREATE operations. The best suitable response
status code for similar requests is 201
Get (REST API)
GET Method
This method is used to get a resource from a server. If you perform
a GET request, the server looks for the data you requested and sends it
back to you. In other words, a GET request performs a READ operation. This
is the default request method.

Assessment: Quiz
The get method is used to send data from the client to the server.

True False
The get method performs a read operation.

True False
The get method is an HTTP method.

True False

Put (REST API)


PUT Method
This request is used to update a resource on a server. If you perform
a PUT request, the server updates an entry in the database and tells you
whether the update is successful or not. In other words, a PUT request
performs an UPDATE operation.
When sending a PUT request, we add a body containing the modification to
be performed.

Assessment: Quiz
The PUT method is used for the update operation.

True False
The update method contains a body.

True False
The PUT method performs an update on a database entity.

True False

Delete (REST API)


DELETE Method
This request is used to delete a resource from a server. If you perform
a DELETE request, the server deletes an entry in the database and tells you
whether the deletion is successful or not. In other words, a DELETE request
performs a DELETE operation.

Assessment: Quiz
To delete a document, we send a PUT request.

True False
The delete method is not a HTTP request, it has to be implemented.

True False
After the delete method is performed, the server sends back a success or failure
response.

True False
Conclusion
Recap
We've learned what a REST API is and how to use POSTMAN to perform a
request with GET, POST, PUT, and DELETE methods. Next, we will learn
how to interact with a REST API in a Node JS application.

You might also like