快速连接mongoose插件到mongodb

我正在尝试在一个快速项目中使用mongoose自动增量插件,并且由于某种原因我无法连接。

这是在我的app.js文件中看起来像

//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"); 

当我运行的应用程序,我得到以下错误

  /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 

这是我得到的时候我console.log我的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 } } 

该程序工作正常,如果我不包括插件。 任何帮助将非常感激。

我有同样的问题,并修复它。

您将连接作为parameter passing给方法“初始化”是不需要的。 在Express或MEAN Stack的Node.js下(我的情况),Mongoose保持自己实例化并与MongoDB连接。 您不需要在app.jsserver.js文件上放置任何东西,只能放在您的model.js文件中。

在插件的文件… / node_modules / mongoose-auto-increment / index.js中,我修改了“初始化”方法。 代码如下:

  // 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; } }; 

现在你可以使用这个文件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); 

现在对我来说工作得很好!

基于文档

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

应该:

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