无法在快递中将mongoose插件连接到mongodb

时间:2014-09-03 17:43:21

标签: node.js mongodb express mongoose

我正在尝试在快速项目中使用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 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 } }

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

2 个答案:

答案 0 :(得分:1)

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

您将连接作为参数传递给方法&#34;初始化&#34;不需要。在具有Express或MEAN Stack(我的情况)的Node.js下,Mongoose保持自身实例化并与MongoDB连接。您不需要在 app.js server.js 文件中放置任何内容,只能在 model.js 文件中。

在插件的文件 ... / node_modules / mongoose-auto-increment / index.js 上,我修改了&#34; initialize&#34;方法。代码如下:

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

现在它对我来说非常好用!

答案 1 :(得分:0)

基于the documentation

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