Step into Mongoosejs - step I

Mongoose: elegant *MongoDB object modeling for node.js.

Installation

1
$npm instll mongoose -g

Connection to MongoDB

best practice

  • opening connection at application start
  • a connection equals a database
  • mongoose model reply on connection being defined
1
2
3
4
5
6
7
8
9
10
// refer mongoos
var mongoose = require("mongoose");

// open a connection to a specific server.db
var connectionString = "mongodb://locahost:27017/testDB";
mongoose.connect(connectionString); //default connection

var connection1 = mongoose.coFateConnection
var connectionString2 = "mongodb://locahost:27017/DB2";
var connection2 = mongoose.createConnection(connectionString2);

Format of connection string / Simple options of connection
Format: mongodb://username:password@domain:port/db

1
2
3
4
5
6
//JSON objects, Options definition
var connectionOptions = {
'username': "db user name",
'password': "db pwd"
};
mongoose.connect(connectionString,connectionOptions);

Close connection

1
2
3
4
5
6
7
8
9
// to close default connection
mongoose.connection.close(callback);
var callback = function(){
console.log('Mongoose\'s connection is closed!');
};

//alternative way to close
connection1.close(callback);
connection2.close(callback);

Events of Connection

a bunch of events list

  • connecting
  • connected
  • open
  • disconnecting
  • disconnected
  • close
  • reconnected
  • error
  • fullsetup
1
2
3
4
5
// how to catch events
connection1.on('error',callback);
var callback = function(){
console.log('[EventName]Error occur!!')
};

Method of connection

  • open(connection_string, [database], [port], [options], [callback])
  • openSet(uris, [database], [options], [callback]), to open the connection to a replica set
  • close([callback])
  • collection(name, [options]), to retrieve a collection(create it if not cached)
  • model(name, [schema], [collection]), to define or retrieve a model
  • modelNames(), return an array of model names created on this connection