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

MongoDB-3

The document discusses Mongoose, an Object Document Model (ODM) for MongoDB that provides structured schema and validation capabilities. It outlines the advantages and disadvantages of using Mongoose, details the schema and its types, and explains how to connect to a MongoDB database. Additionally, it covers REST API principles, including request methods, response standards, and best practices for API design and testing.

Uploaded by

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

MongoDB-3

The document discusses Mongoose, an Object Document Model (ODM) for MongoDB that provides structured schema and validation capabilities. It outlines the advantages and disadvantages of using Mongoose, details the schema and its types, and explains how to connect to a MongoDB database. Additionally, it covers REST API principles, including request methods, response standards, and best practices for API design and testing.

Uploaded by

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

MONGODB -3

SUNITA D RATHOD
Using Mongoose for Structured Schema
and Validation
• Mongoose is an Object Document Model (ODM) that
pipes additional functionality onto the native driver.

• It simply applies a more structured schema to a collection


and allows for additional validation and typecasting of
variables.

• Mongoose will only enhance this driver with greater


functionalities.
Advantages of Mongoose
• A schema can be created for your documents.

• Documents in the model can be successfully validated.

• Data can be typecast as needed.

• Business logic ca be hooked via middleware.

• Mongoose is easier to learn than the node.js driver.


Disadvantages of Mongoose
• A schema is mandatory which is hassle when one is not
needed.

• Operation like storing data are performed with more


efficiency by the node.js driver than by mongoose
New objects introduced by mongoose
• Mongoose is situated right above the node.js driver and
adds some new objects to it.

• Schema object

• Model object

• Document object
New objects introduced by mongoose
• Schema object: defines the needed structure for the
documents in a given collection.

• Its aids in the definition of fields and datatypes to add


indexing or any validation to them.

• Model object: is just a representation of the documents


present in a collection.

• Document object: is the representation of any individual


document in a collection.
Connecting to the MongoDB Database
• For connection to Mongoose, We use similar connection
string to node.js.

• Lets see how to import mongoose, connect to the


database, wait for open events and then display the
connection present in the database before disconnecting
Connecting to the MongoDB Database
let mongoose = require('mongoose');
mongoose.connect(‘monngodb://localhost/mywords’);
mongoose.connection.on(‘ open’, function() {
console.log(mongoose.connection.collection);
mongoose.connection.db.collectionNames(function
(error, names){
console.log(mynames);
mongoose.disconnect();
});
});
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.
Schema Types
The following Schema Types are permitted:

• Array
• Boolean
• Buffer
• Date
• Mixed (A generic / flexible data type)
• Number
• ObjectId
• String
Creating a Mongoose schema
• To create schema , we need a new instance of the
schema object.

• The first parameter accepts an object describing the


schema.

• The second parameter are the options available when


defining a schema as shown in table in next slide

var student_schema= new Schema( { object}, {options});


Options available
Options Description

autoIndex Boolean – auto indexed is turned off


BufferCommands Boolean – commands cannot be completed due to buffering
server
Capped maximum no. of documents
Collection collection name for schema
Id Boolean – document id >id value
Read specify replica read preference like primary, primary
preferred, secondary preferred or nearest
Safe Boolean – mongoose applies write concern to request that
update to data base.
Strict Boolean – attributes passed that are not parts of the
schema are not saved
Mongoose Schema
• We can add index fields, unique fields, required fields.
• We can also add methods to schema

var myschema = new Schema ({


name: {type : string, index:1, unique: true, required: true},
first : String,
Last : String
});
Schema.method.nam= function()
{
return this.first+” ”+this.last;
};
Mongoose Validators
• Validators validate the value before storing it to the database.
Example:
Number Schema Types Properties
Example:
Full fledged example:

Alert message
Full fledged example:
Expalination:
• We validated Schema types using built-in validators, we
can also pass the alert messages if the validation is failed.

• As per the name example, we set the minLength to 4, if


the length is less than the required numbers than the alert
message will be displayed to the user.

• The model() function is a part of the mogoose model. The


function uses the syntax- model(name, [schema]).

• The first parameter is a string that is used to find the


model and the second parameter is the schema object.
The rules of a REST API
• REST stands for REpresentational State Transfer, an
architectural style which is stateless, meaning it has no
idea of any current user or their history of interactions.

• API stands for Application Program Interface, which


allows application to “talk” or interact with each other.

• The REST API is the stateless interface to the database


and allows a application to work on the data.
REST API
• The REST API takes an incoming HTTP request,
performs its processing and always sends back a HTTP
response.
REST API Standards
• Request URLs

• Request Methods

• Response and Status code


Request URLs
• A request URL consists of an HTTP method, a base URL,
and a resource URI.

• We have a set of API URLs for each collection. You may


also have a set of URLs for each set of subdocuments.

• Use the following format to construct a request URL:


• <HTTP method> http(s)://<host>:<port>/api/public/<resource URI>

• The following example shows a URL for a request that


returns a list of all projects:
• GET http://<host name>:<port number>/api/public/tdm/v1/projects

Request Methods
• HTTP request can have different methods that notify the
server of what actions needs to be taken.

Request Method Use Response

POST To create data in the The new data object


database created
GET To read data from the Data object that answered
database the request
PUT To update data in the The newly updated data
database
DELETE To delete data from the Nothing
database
• Request methods that link URLs to the desired actions,
enabling the API to use the same URL for different actions

Action Method URL path Example


Create new POST /locations http://loc8r.com/api/locations
location
Read list of GET /locations http://loc8r.com/api/locations
locations
Read a GET /locations/:locationid http://loc8r.com/api/locations/123
specific
location
Update a PUT /locations/:locationid http://loc8r.com/api/locations/123
specific
location
Delete a DELETE /locations/:locationid http://loc8r.com/api/locations/123
specific
location
Response and Status code

A good API always returns a response and shouldn’t leave you hanging.
Response and Status code
• Standardizing the API is just as important as the API
request format.

• The response has two parts –


• The returned data
• The HTTP status code

• API returns data in a consistent format and the typical


data formats are XML and JSON

• JSON is more compact than XML and is usually a better


format for faster responses
Response and Status code
• The response will have one of the three things
• The actual response data
• Error data, or
• A null response

• A good and well designed API should send back HTTP


status codes.

• The most famous one that we all know is “404” – Page


Not Found.
HTTP status
• These are the few which are very familiar to the user :

• 200: Success

• 201: Created

• 401: Unauthorized

• 403: Forbidden

• 404: Not found

• 429: Too many requests

• 500: Server Error


Evaluating API Patterns
• Understanding API patterns is all about keeping score of
things that make an API easy to design, understand, build
and maintain.

• Using Friendly Endpoint Names


• A very typical way to design an API pattern is to create the
API’s endpoint around what resources are available.

• The HTTP methods are the verbs and the resources are
the nouns. The names you use must be as descriptive as
you can make them.
Evaluating API Patterns
• GET vs. POST
• When the API is being designed, we want to make use of
the HTTP methods for any call.

• The use case of the call should determine what is to be


used.

• Choosing the right method is an essential part of REST


API patterns.
Best Practices for API URLs
• The URLs describe resources and the HTTP verbs
describe what actions can be performed.

• So, the URLs must always contain nouns and never


verbs.

• The nouns will describe the domain model


CRUD
• CRUD is a very common acronym that comes from
databases management.

• Each letter describes an operation like Create, Read,


Update and Delete.

• Every URL points to a set of data and the data can be


accessed with different HTTP verbs like GET, POST, PUT
and DELETE.

• Lets see how HTTP verbs relate to CRUD.


POST
• POST is the verb used to create new data(resources).

• POST can assign a new ID (Uniform Resource Identifier)


to newly added resource.

• HTTP status 201 is returned if the resource is created


successfully.

• POST method is neither safe or idempotent.

• Example: POST http://www.abc.com/employees


GET
• GET method is used to read or retrieve a resource.

• If HTTP status code returned is as


• 200 – means “OK” - data is received successfully
• 404 – means “Not Found”- call results in error
• 400 – means “Bad Request”- call results in error

• GET is considered idempotent – means it will return the


same value if called once or many times.

• Example: GET http://www.abc.com/employees/tushar


PUT
• PUT is used for updating resource values

• HTTP status returns


• 200 – means Successful Request
• 204 – means Successful Request with no Content Returned

• PUT method is not a safe operation.

• PUT request is however, is idempotent.

• Example: PUT http://www.abc.com/employees/tushar


DELETE
• DELETE is used for deleting a resource.

• HTTP status code returns


• 200 – means resource is deleted successfully
• 204 – means Successful Request with no Content Returned.
• 404 – means “ Not Found”

• DELETE request are idempotent.

• Example: DELETE http://www.abc.com/employees/tushar


Testing API Endpoints
• We test to ensure that the API endpoints are stable, safe and
display expected behavior.

• Functional API Endpoint Testing


• Functional testing is aimed at verifying that the request, state and
response of the endpoint is working as expected as per feature
specification

• Test HTTP status code


• Test Response object
• Test Happy Paths
• Negative Testing
• Destructive Testing
• Combine API with UI Testing
• Test Security and Authorization
Testing API Endpoints
• Non-Functional (performance) Testing
• Non-Functional testing of an API endpoints focuses on the speed,
stability and scalability of API

• Check Response Times


• Check CPU Utilization
• Check Memory Utilization
• Check Disk Time
Testing API Endpoints
• API Endpoint Load Testing
• Load testing is used to measure how well the API works when a
massive number of API requests hit the server together.

• Performance–ready API
• Evaluate specific servers
• Cost and Time Effectiveness
Thank you

You might also like