cklanac
8/9/2017 - 9:53 PM

Experiments with Mongoose Buffering

Experiments with Mongoose Buffering

'use strict';

/**
 * Experiments with [Mongoose Buffering](http://mongoosejs.com/docs/connections.html#buffering)
 * 
 * Also handle:
 *    "DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` 
 *    instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`.
 *    See http://mongoosejs.com/docs/connections.html#use-mongo-client"
 * v4.10.8 and lower:
 * - useMongoClient NOT required
 * v4.11
 * - pass `useMongoClient: true` in connection options
 * 
 */

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;

console.log('start connection');
mongoose.connect('mongodb://localhost/scratchpad', {
  useMongoClient: true
}).then(function () {
  console.log('database connected');
});

console.log('create model');
var Cat = mongoose.model('Cat', { name: String });

console.log('create new document');
var kitty = new Cat({ name: 'Zildjian' });

console.log('document save');
kitty.save()
  .then((res) => {
    console.log('document saved');
    console.log(res);
  })
  .catch((err) => {
    console.log('document error');
    console.error(err);
  });

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