9. Mongoose(Key Methods of API)

Objectives :In the this section, we’re going to Learn the key method of API in mongoose .

Key Terms

  • Connect
  • Schema
  • model
  • createconnection
  • open
  • openset
  • readystate

Key Methods and Properties of Mongoose

>_ connect()

Opens the default mongoose connection.
Syntax:
connect(uri(s), [options], [callback])
Example:

1 var mongoose=require('mongoose');
2 mongoose.connect("mongodb://mongodb.tutorialtous.com/mongoose",function(error){
3   if(error){
4     console.log("error"+error);
5   }else{
6     console.log("open done")
7   }
8 });

Note:-

  • Once we call this method it will call Connection’s open() or openSet() method.
  • When connection success ‘connection’ property is set with the opened connection. Means ‘mongoose.connection’ will holds connection information.

Check this example for clarity

1 mongoose.connect("mongodb://mongodb.tutorialtous.com/mongoose",function(error){
2 console.log("open done"+mongoose.connection.host+"\t"+ mongoose.connection.port)
3   if(error){
4     console.log("error"+error);
5   }else{
6   }
7 });

In the above after connection open it will echos connection’s host and port details.

>_ createConnection()

Will creates a connection instance and its work is similar to connect() mentioned above
Syntax:
createConnection([uri], [options], [options.config], [options.config.autoIndex])
Note:-

  • All arguments are optional for this method.
  • returns mongoose.Db property
  • If have uri and other arguments it will proxy(calls) connection.open() or connection.openSet().
  • If we doesn’t pass any arguments using the returned mongoose.Db’s open(),openSet() method we can open connections.

Example:

1 var mongoose= require("mongoose");
2 var db =mongoose.createConnection("mongodb://mongodb.tutorialtous.com/mongoose",
3   function(error){if(!error){
4   console.log("open connection done");
5   }});
1 var mongoose= require("mongoose");
2 var db = mongoose.createConnection();
3 db.open("mongodb://mongodb.tutorialtous.com/mongoose",function(error){
4   if(!error){
5   console.log("open connection done");
6   }
7 });

>_ Schema()

The Mongoose Schema constructor
Syntax:
Schema()
Example:-

1 var mongoose=require('mongoose');
2 var MySchema = mongoose.Schema;
3 var schemaref = new MySchema();

>_ Model()

The Mongoose Model constructor..

>_ Document()

The Mongoose Document constructor.

>_ disconnect()

Disconnects all connections.

Syntax:-
Disconnect([function])

Mongoose Connection

open()

Opens the connection to MongoDB.

Syntax:-
open(connection_string, [database], [port], [options], [callback])

  • connection_string <String> mongodb://uri or the host to which we are connecting
  • [database] <String> database name //optional
  • [port] <Number> database port //optional
  • [options] <Object> options //optional
    • db, server, replset, user, pass, auth are the options
  • [callback] <Function> //optional

Example:-

1 var mongoose=require('mongoose');
2 var con = mongoose.createConnection();
3 var cb = function(err){
4   if(!err)
5     console.log(err);
6   else
7   console.log("connection opened");
8 };

>_ openSet()

Opens the connection to a replica set.

Syntax:-
openSet(uris, [database], [options], [callback])

  • uris <String> comma-separated mongodb:// URIs
  • [database] <String> database name if not included in uris
  • [options] <Object> passed to the internal driver
  • [callback] <Function>

Note:-
Functionality of openSet() will be similar to open() except openSet() works with replicaSets

Check this Example

01 var mongoose=require('mongoose');
02 var con = mongoose.createConnection();
03 var cb = function(err){
04   if(!err)
05     console.log(err);
06   else
07   console.log("connection opened");
08 };
09 con.openSet("mongodb://localhost/tutorialtous,
10 mongodb://mongodb.tutorialtous.com:23396/tutorialtous",cb);

>_ close()

Closes the connection, it doesn’t throw any error even the connection is not opened or already closed.

Syntax:-
close([callbackfunction]);

Example:-

01 var mongoose=require('mongoose');
02 var con = mongoose.createConnection();
03 var cb = function(err){
04   if(!err)
05     console.log(err);
06   else
07   console.log("connection opened");
08 };
09 var ccb = function(err){
10   if(!err)
11     console.log(err);
12   else
13   console.log("connection closed");
14 };
16 con.close(ccb);
17 console.log("connection opened");
18 console.log(err);
19 console.log("connection closed");
20 console.log(err);

>_ readyState

It is property of connection which holds state of the connection

State Description
0 disconnected
1 connected
2 connecting
3 disconnecting

When this concept (readyState) is useful:

Due to network interrupt at server/client side or server down time connection to the database may lose, in order to trace those situations we need to use the readyState concept.

Let check this example

01 var mongoose=require('mongoose');
02 var con = mongoose.createConnection();
03 var connecting = function(err){
04 console.log("Please Wait connecting \t"+con.readyState);
05 };
06 var disconnecting = function(err){
07 console.log("Please Wait Disconnecting \t"+con.readyState);
08 };
09 var connected = function(err){
10 console.log("Connection Connected\t"+con.readyState);
11 };
12 var disconnected= function(err){
13 console.log("Connection DisConnected \t"+con.readyState);
14 };
15 con.on("connecting",connecting);
16 con.on("disconnecting",disconnecting);
17 con.on("connected",connected);
18 con.on("disconnected",disconnected);

 

If the mongo server is up state then we will get this output:-
Please Wait connecting 2
Connection Connected 1

Now disable net connection at client machine or stop the server if both client and server running in same machine. Then you will observe the following message

Connection DisConnected 0
While doing the practical application it is very helpful based on my work experience.

 

Mongoose Schema

Constructor

Defines a schema with the definition. Definition of the schema need to in bson form. Means {fieldname :{field options}}

Syntax :- Schema(definition, [options])

Some key options are

  • autoIndex: bool – defaults to null (which means use the connection’s autoIndex option)
  • capped: bool – defaults to false
  • collection: string – no default (collection name that we need)
  • versionKey: string – defaults to “__v”

example :-

1 var userSchema= new Schema({
2   userid: {type:String, required:true, trim:true},
3   chips: {type:Number}
4 });

Notes:-

  • Mongoose will add ‘s’ letter to the collection . means if collection name is ‘user’ then it will be saved as ‘users’.
  • If we need to give custon naming (without s) then use ‘collection’ option as
    new Schema({…..},{collection:user});

>_ Add()

If we want to add the filed to a defined schema we can do this using Add() method.

It’s syntax is:
add(obj,prefix)

Example:-
for the above userSchema now I need to add the fields

  1. ‘regdate’ to hold date of registration
  2. ‘usertype’ to indicate user is player or promoter (agent)
1 userSchema.add({
2   regdate:Date, usertype:{type:string,default:'player'}
3 });

>_ get()

get the value of schema option. Means to know the value of an option which is defined for a schema we can use this.
For example I need to know does the collection is capped or not then I will use the get() method with capped option to know capped status.

Syntax:  get(optionkey)

Example:

1 console.log(userSchema.get('capped'));
2 console.log(userSchema.get('autoIndex));

>_ set()

Sets/gets a schema option.
Syntax:   set(key, [value])

Example:

1 userSchema.set('capped',false);
2 userSchema.set('strict',false);

>_ index()

Defines an index for the schema, means if we want to create an index to a schema then we can do using this method.
Compound index creation is not possible at schema definition (in schema() or add()) using index() method only we can create compound index.

Syntax:
index(fields, [options], [options.expires=null])

Note:-
Here options refers MongoDB index options like ‘unique’,’sparse’,’name’,’expireAfterSeconds’ etc.

Example:-

Create an index for the userid to userSchema.

1 userSchema.index({userid:1},{name:'useridindex',unique:true})

>_ method()

How to create an instance method for a schema in mongoose
Adds an instance method to documents constructed from Models compiled from this schema.
In order to add a method to a schema then we will use this.

Syntax:
method(methodname, function code)

Example:-

01 var userSchema= new Schema({
02   userid: {type:String, required:true, trim:true},
03   chips: type:Double
04 });
05 userSchema.method('getInfo',function(){
06   console.log(“userid:\t”+this.userid+”\tchips own:\t”+this.chips);
07 });
08 userSchema.method('getChips',function(){
09   return this.chips;
10 });

Example to call those methods:-

1 var userModel = mongoose.model('users',userSchema);
2 var alex = new userModel({userid:'Alex',chips:10000,regdate:Date.now});
3 alex.getInfo();
4 console.log(alex.getChips());

>_ static()

How to create an instance method for a schema in mongoose
Adds static “class” methods to Models compiled from this schema.

Syntax:-
static(method name,function def);
Example:-

1 userSchema.static('getSchemaName',function(){
2   return 'users';
3 });
4 userSchema.static('saveDoc',function(query){
5   // some coding
6 });

Way to call static methods:-

Schemaname.staticmethodname
Like
console.log(userSchema.getSchemaName());

Mongoose Model

>_ Constructor Model()

Model constructor

Syntax:
Model(doc)

>_ save()

Saves the document.

Syntax:- save([options], [options.safe], [options.validateBeforeSave], [fn])

01 var mongoose=require('mongoose');
02 var Schema = mongoose.Schema;
03 var con ;
04 var userSchema= new Schema({
05   userid: {type:String, required:true, trim:true,index:true,unique:true},
06   chips: {type:Number}
07 });
08
09 var userModel = mongoose.model('users',userSchema);
10 var alex = new userModel({userid:'Alex',chips:10000,regdate:Date.now});
11 var cb = function(err){
12   if(!err)
13     console.log("Connection Opened");
14   else
15     console.log("Connection Opened Failed");
16   };
17 mongoose.connect("mongodb://localhost/tutorialtous",cb);
18 con = mongoose.connection;
19 alex.save(function(err,alex){
20   if(err){
21     console.log(err);
22   }else{
23     console.log("Document Save Done");
24   }
25
26 });

>_ find()

Find the documents of a collection/model.
Note:-
We need to call find() methods with Model Instances unlike save(), means like userModel.find() is valid.

Syntax:- find(conditions, [projection], [options], [callback])

Conditions, projection, options are similar to mongodb’s find() method.
Example:-

01 var mongoose=require('mongoose');
02 var Schema = mongoose.Schema;
03 var con ;
04 var userSchema= new Schema({
05   userid: {type:String, required:true, trim:true,index:true,unique:true},
06   chips: {type:Number}
07 });
08
09 var userModel = mongoose.model('users',userSchema);
10 var alex = new userModel({userid:'Alex',chips:10000,regdate:Date.now});
11 var mark = new userModel({userid:'Mark',chips:15000,regdate:Date.now});
12
13 var cb = function(err){
14   if(!err){
15     console.log("connection opened \t"+con.readyState);
16   }else{
17     console.log(err);
18   }
19 };
20
21 mongoose.connect("mongodb://localhost/tutorialtous",cb);
22 con = mongoose.connection;
23  
24 var echoRecords =function(err,log){
25   console.log("Total Records Found:"+log.length);
26   for(var i=0;i<log.length;i++){
27     console.log((i+1)+"\t"+log[i]._id+"\t"+log[i].userid+"\t"+log[i].chips);
28   }
29 };
30
31 var saveResponse =function(err){
32   if(err){
33   console.log("save Failed");
34   }else{
35   console.log("save success");
36   }
37 };
38
39 alex.save(saveResponse);
40 mark.save(saveResponse);
41
42 userModel.find(echoRecords);
43 userModel.find({userid:"Alex"},echoRecords);
44 userModel.find({userid:"Alex"},{_id:0},echoRecords);

 

>_ update()

Updates documents in the database without returning them.
Syntax:-
update(conditions, doc, [options], [callback])
Example:-

1 userModel.update({userid:"Alex"},{chips:25000},function(err,log){
2 console.log("Number of Records Effected"+log);
3 });
4
5 userModel.update({chips:{$lt:20000}},{chips:35000},{multi:true},function(err,log){
6 console.log("Number of Records Effected"+log);
7 });

It will returns number of documents updated count

 

>_ remove()

Removes document/s from the collection.

Syntax:-
remove(conditions, [callback])
Note:-
1. If condition not passed or empty then all the records will be removed.

Example:-
1. Remove the document having userid “Alex”

1 userModel.remove({userid:"Alex"})

2. Remove all documents of users collection

1 userModel.remove()

 

>_ findOne()

Finds a single document by its _id field.

Syntax:-
findOne([conditions], [projection], [options], [callback])
Example:-
1.Find the user details having the id “57971362517cdfd0260a638c”

1 userModel.findOne({_id:"57971362517cdfd0260a638c"},"chips,userid",
2   function(err,data){if(!err) console.log(data);});

 

>_ findOneAndRemove()

Issue a mongodb findAndModify remove command.

Syntax:-
findOneAndRemove(conditions, [options], [callback])
Example:-
1. Remove the user details having the id “57971362517cdfd0260a638c”

1 userModel.findOneAndRemove({_id:"57971362517cdfd0260a638c"},
2   function(err,data){if(!err) console.log(data);});

 

>_ findByIdAndUpdate()

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed else a Query object is returned.

Syntax:-
findByIdAndUpdate(id, [update], [options], [callback])
Example:-
1. Reset the chips for the id “5797137d0856a7c41299e099”

1 userModel.findByIdAndRemove("5797137d0856a7c41299e099",
2 {chips:0},function(err,data){if(!err) console.log(data);});

 

>_ findById()

Finds a single document by its _id field. findById(id).

Syntax:-
findById(id, [projection], [options], [callback]) Example:-
1.Find the user details having the id “57971362517cdfd0260a638c”

1 userModel.findById("57971362517cdfd0260a638c","chips,userid",
2   function(err,data){if(!err) console.log(data);});

 

>_ findByIdAndRemove()

Issue a mongodb findAndModify remove command by a document’s _id field. findByIdAndRemove(id, …) is equivalent to findOneAndRemove({ _id: id }, …).

Syntax:-
findByIdAndRemove(id, [options], [callback])
Example:-
1. Remove the user details having the id “57971362517cdfd0260a638c”

1 userModel.findByIdAndRemove("57971362517cdfd0260a638c",
2   function(err,data){if(!err) console.log(data);});

 

>_ findByIdAndUpdate()

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes immediately if callback is passed else a Query object is returned.

Syntax:-
findByIdAndUpdate(id, [update], [options], [callback])
Example:-
1. Reset the chips for the id “5797137d0856a7c41299e099”

1 userModel.findByIdAndRemove("5797137d0856a7c41299e099",
2   {chips:0},function(err,data){if(!err) console.log(data);});

 

>_ count()

Counts number of matching documents in a database collection.

Syntax:-
count(conditions, [callback])
Example:-
1. Find Number of Documents in users Schema

1 userModel.count({},function(err,count){
2   console.log("No Of Records in users Schema:"+count);
3 });

 

2. Find Number of Documents in users Schema having chips<=25000

1 userModel.count({chips:{$lte:25000}},function(err,count){
2   console.log("chips <=25000 :"+count);
3 });

 

>_ where()

Creates a Query, applies the passed conditions, and returns the Query.

Syntax:-
where(path, [val])
Example:-
1. Find the users having chips <10000

1 userModel.where('chips').lt(10000);

2. Find the users having chips <10000 of Country ‘USA’

1 userModel.where('chips').lt(10000).where('country').eq('USA');

Complete Example:-

01 var mongoose=require('mongoose');
02 var Schema = mongoose.Schema;
03 var con = mongoose.createConnection();
04 var userSchema= new Schema({
05   trim:true,index:true,unique:true},
06 });
07 var userModel = mongoose.model('users',userSchema);
08   userid: {type:String, required:true,
09   chips: {type:Number}
10 var echo=function(err,log){
11   if(!err){
12   console.log(log);
13   }
14 }
15 mongoose.connect("mongodb://localhost/tutorialtous",cb);
16 con = mongoose.connection;
17 userModel.where('chips').lt(10000)
18   .where('country').eq('USA').exec(echo);