Key Methods and Properties of Mongoose

>_ connect()

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

var mongoose=require('mongoose');
mongoose.connect("mongodb://mongodb.tutorialtous.com/mongoose",function(error){
  if(error){
    console.log("error"+error);
  }else{
    console.log("open done")
  }
});
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

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

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:

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

>_ Schema()

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

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

>_ Model()

The Mongoose Model constructor..
Check this link to know about Model’s Constructor and other methods

>_ Document()

The Mongoose Document constructor.
Check this link to know about Document Constructor and other methods

>_ disconnect()

Disconnects all connections.

Syntax:-
   Disconnect([function])

Copyright © 2018-2020 TutorialToUs. All rights reserved.