Cannot connect mongoose plugin to mongodb in express

I am trying to use mongoose auto increment plugin in an express project and i can't connect for some reason.

This is what looks like in my app.js file

    //dependencies
var config = require('./config'),
    express = require('express'),
    session = require('express-session'),
    mongoStore = require('connect-mongo')(session),
    http = require('http'),
    path = require('path'),
    passport = require('passport'),
    mongoose = require('mongoose'),
    autoIncrement = require('mongoose-auto-increment'),
    helmet = require('helmet');

var stripe = require("stripe")("sk_test_nEgbqClEavLcf8zGIj4GtaOy");

//create express app
var app = express();


//keep reference to config
app.config = config;

//setup the web server
app.server = http.createServer(app);

//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
  //and... we have a data store
});

//add plugin for autoincrement 
autoIncrement.initialize("mongodb://localhost:27017/prwrite");

When i run the app, i get the following error

    /home/kseguy/node_projects/prwrite/node_modules/mongoose-auto-increment/index.js:27
            throw ex;
                  ^
TypeError: Object mongodb://localhost:27017/prwrite has no method 'model'
    at Object.exports.initialize (/home/kseguy/node_projects/prwrite/node_modules/mongoose-auto-increment/index.js:10:38)
    at Object.<anonymous> (/home/kseguy/node_projects/prwrite/app.js:36:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

This is what i get when i console.log my app.db

    { base: 
   { connections: [ [Object], [Circular] ],
     plugins: [],
     models: {},
     modelSchemas: {},
     options: { pluralization: true } },
  collections: {},
  models: {},
  replica: false,
  hosts: null,
  host: 'localhost',
  port: 27017,
  user: undefined,
  pass: undefined,
  name: 'prwrite',
  options: 
   { db: { read_preference: 'primary', forceServerObjectId: false, w: 1 },
     auth: {},
     server: { socketOptions: [Object], auto_reconnect: true },
     replset: { socketOptions: {} } },
  otherDbs: [],
  _readyState: 2,
  _closeCalled: false,
  _hasOpened: false,
  _listening: false,
  _events: 
   { error: [Function],
     open: { [Function: g] listener: [Function] } },
  db: 
   { domain: null,
     _events: {},
     _maxListeners: 10,
     databaseName: 'prwrite',
     serverConfig: 
      { domain: null,
        _events: {},
        _maxListeners: 10,
        _callBackStore: [Object],
        _commandsStore: [Object],
        auth: [Object],
        _dbStore: [Object],
        host: 'localhost',
        port: 27017,
        options: [Object],
        internalMaster: false,
        connected: false,
        poolSize: 5,
        disableDriverBSONSizeCheck: false,
        _used: true,
        replicasetInstance: null,
        emitOpen: true,
        ssl: false,
        sslValidate: false,
        sslCA: null,
        sslCert: undefined,
        sslKey: undefined,
        sslPass: undefined,
        serverCapabilities: null,
        name: 'localhost:27017',
        socketOptions: [Object],
        logger: [Object],
        eventHandlers: [Object],
        _serverState: 'connecting',
        _state: [Object],
        recordQueryStats: false,
        socketTimeoutMS: [Getter/Setter],
        db: [Circular],
        dbInstances: [Object],
        connectionPool: [Object] },
     options: { read_preference: 'primary', forceServerObjectId: false, w: 1 },
     _applicationClosed: false,
     slaveOk: false,
     bufferMaxEntries: -1,
     native_parser: undefined,
     bsonLib: 
      { Code: [Function: Code],
        Symbol: [Function: Symbol],
        BSON: [Object],
        DBRef: [Function: DBRef],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Function: Double],
        MinKey: [Function: MinKey],
        MaxKey: [Function: MaxKey],
        promoteLongs: true },
     bson: { promoteLongs: true },
     bson_deserializer: 
      { Code: [Function: Code],
        Symbol: [Function: Symbol],
        BSON: [Object],
        DBRef: [Function: DBRef],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Function: Double],
        MinKey: [Function: MinKey],
        MaxKey: [Function: MaxKey],
        promoteLongs: true },
     bson_serializer: 
      { Code: [Function: Code],
        Symbol: [Function: Symbol],
        BSON: [Object],
        DBRef: [Function: DBRef],
        Binary: [Object],
        ObjectID: [Object],
        Long: [Object],
        Timestamp: [Object],
        Double: [Function: Double],
        MinKey: [Function: MinKey],
        MaxKey: [Function: MaxKey],
        promoteLongs: true },
     _state: 'connecting',
     pkFactory: 
      { [Function: ObjectID]
        index: 7803230,
        createPk: [Function: createPk],
        createFromTime: [Function: createFromTime],
        createFromHexString: [Function: createFromHexString],
        isValid: [Function: isValid] },
     forceServerObjectId: false,
     safe: false,
     notReplied: {},
     isInitializing: true,
     openCalled: true,
     commands: [],
     logger: { error: [Function], log: [Function], debug: [Function] },
     tag: 1409765208948,
     eventHandlers: 
      { error: [],
        parseError: [],
        poolReady: [],
        message: [],
        close: [] },
     serializeFunctions: false,
     raw: false,
     recordQueryStats: false,
     retryMiliSeconds: 1000,
     numberOfRetries: 60,
     readPreference: undefined } }

The program works fine if i dont include the plugin. Any help will be really appreciated.

Based on the documentation

//add plugin for autoincrement 
autoIncrement.initialize("mongodb://localhost:27017/prwrite");

Should be:

app.db = mongoose.createConnection(config.mongodb.uri);
// ...
//add plugin for autoincrement 
autoIncrement.initialize(app.db);

I had the same issue and fix it.

You to pass the connection as parameter to the method "initialize" is unneeded. Under Node.js with Express or MEAN Stack (my case), the Mongoose keep itself instantiated and connected with MongoDB. You don't need put nothing on app.js or server.js file, only in your model.js file.

On file .../node_modules/mongoose-auto-increment/index.js of plugin, I modify the "initialize" method. The code is below:

    // Module Scope
var mongoose = require('mongoose'),
    extend = require('extend'),
    Schema = mongoose.Schema,
    counterSchema,
    IdentityCounter;

// Initialize plugin by creating counter collection in database.
exports.initialize = function () {
    try {
        IdentityCounter = mongoose.model('IdentityCounter');
    } catch (ex) {
        if (ex.name === 'MissingSchemaError') {
            // Create new counter schema.
            counterSchema = new Schema({
                model: { type: String, require: true },
                field: { type: String, require: true },
                count: { type: Number, default: 0 }
            });

            // Create a unique index using the "field" and "model" fields.
            counterSchema.index({ field: 1, model: 1 }, { unique: true, required: true, index: -1 });

            // Create model using new schema.
            IdentityCounter = mongoose.model('IdentityCounter', counterSchema);
        }
        else
            throw ex;
    }
};

Now you can use this code example of file contact.server.model.js:

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    autoIncrement = require('mongoose-auto-increment');

autoIncrement.initialize();

/**
 * Contact Schema
 */
var ContactSchema = new Schema({
    name: {
        type: String,
        default: '',
        required: 'Please fill Contact name',
        trim: true
    },
    created: {
        type: Date,
        default: Date.now
    },
    user: {
        type: Number,
        ref: 'User'
    }
});

ContactSchema.plugin(autoIncrement.plugin, {
    model: 'Contact',
    field: '_id',
    startAt: 1,
    incrementBy: 1
});
mongoose.model('Contact', ContactSchema);

Now it's working very well for me!