What is Mongoose?
- Mongoose is an object modelling package for Node that essentially works like an ORM (Object-relational mapping ) that you would see in other languages.
- Mongoose allows us to have access to the MongoDB commands for CRUD simply and easily.
Mongoose Installation
- npm install mongoose --save
What is Schema?
- "Mongoose Schema will create a mongodb collection and defines the shape of the documents within that collection".
- If we want to create a mongodb collection in a structured manner similar to SQL tables then we can do that using mongoose Schema.
- In the schema creation we will specify the details of fields like field name, its type, default value if need, index concept if need, constraint concept if need.
What is the Model?
- Schemas define a structure we will apply that Schema part to a model, means "Models are the constructors compiled from our schema definitions".
- Instances of these models represent documents which can be saved and retrieved from our database. All document creation and retrieval from the database is handled by these models.
Key Methods and Properties of Mongoose
Connect() :- Opens the default mongoose connection.
CreateConnection() :-Will creates a connection instance and its work is similar to connect()
Schema():-The Mongoose Schema constructor
CreateConnection() :-Will creates a connection instance and its work is similar to connect()
Schema():-The Mongoose Schema constructor
Model():-The Mongoose Model constructor
Document() :-The Mongoose Document constructor.
Disconnect():- Disconnects all connections.
Open(): Opens the connection to MongoDB.
OpenSet(): Opens the connection to a replica set.
close() : Closes the connection, it doesn’t throw any error even the connection is not opened or already closed.
readyState : It is the property of connection which holds the state of the connection.
Mongoose Schema
- constructor
syntax:- Schema(definition, [options])
Example
Example
- add ( )
syntax:- add(obj,prefix)
Example
Example
- get ( )
syntax:- get(optionkey)
Example
Example
- set ( )
syntax:- set(key, [value])
Example
Example
- index ( )
syntax:- index(fields, [options], [options.expires=null])
Example
- method ( )
syntax:- method(methodname, function code)
Example
- static ( )
syntax:- static(method name,function def);
Example
- pre ( )
- post ( )
- Constructor Model( )
syntax:- Model(doc)
- save ( )
syntax:- save([options], [options.safe], [options.validateBeforeSave], [fn])
Example
- find ()
Syntax:- find(conditions, [projection], [options], [callback])
- update ( )
Syntax:- update(conditions, doc, [options], [callback])
Example
- remove ( )
Syntax:- remove(conditions, [callback])
No comments:
Post a Comment