Skip to content

Instantly share code, notes, and snippets.

@suissa
Created August 26, 2014 23:38
Show Gist options
  • Select an option

  • Save suissa/1058f338ee628d7c60e2 to your computer and use it in GitHub Desktop.

Select an option

Save suissa/1058f338ee628d7c60e2 to your computer and use it in GitHub Desktop.

Revisions

  1. suissa created this gist Aug 26, 2014.
    37 changes: 37 additions & 0 deletions mongoose-connection-best-practices
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    // Bring Mongoose into the app
    var mongoose = require( 'mongoose' );

    // Build the connection string
    var dbURI = 'mongodb://localhost/mongoose-best-practices';

    // Create the database connection
    mongoose.connect(dbURI);

    // CONNECTION EVENTS
    // When successfully connected
    mongoose.connection.on('connected', function () {
    console.log('Mongoose default connection open to ' + dbURI);
    });

    // If the connection throws an error
    mongoose.connection.on('error',function (err) {
    console.log('Mongoose default connection error: ' + err);
    });

    // When the connection is disconnected
    mongoose.connection.on('disconnected', function () {
    console.log('Mongoose default connection disconnected');
    });

    // When the connection is open
    mongoose.connection.on('open', function () {
    console.log('Mongoose default connection is open');
    });

    // If the Node process ends, close the Mongoose connection
    process.on('SIGINT', function() {
    mongoose.connection.close(function () {
    console.log('Mongoose default connection disconnected through app termination');
    process.exit(0);
    });
    });