1

I tried to connect mongodb. But I couldn't it. I thought [autoIncrement.initialize] is problem, but I couldn't solve the problem. This is my code.

const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
require('dotenv').config();

mongoose.Promise = global.Promise;

const connect = mongoose.connect(process.env.MONGODB_URI);
autoIncrement.initialize(connect);

Here is error traceback:

/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:27
      throw ex;
      ^

TypeError: connection.model is not a function
    at Object.exports.initialize (/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:10:34)
    at Object.<anonymous> (/Users/loo/Projects/example-app/app.js:8:15)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:238:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)
num8er
  • 18,604
  • 3
  • 43
  • 57
ㄴㅇㅇ
  • 67
  • 2
  • 4
  • 8
  • The title suggests that there is more code than that. Is it ? – mexo Jul 04 '18 at 23:58
  • 1
    @mexo it's normal question. since mongoose-auto-increment module tries to access `.model` method of connection that is passed as an argument in `.initialize` method call. In fact LOO should add error traceback for more information. But problem should be solved using example in my answer. – num8er Jul 05 '18 at 00:07
  • @mexo I've added additional info (; – num8er Jul 05 '18 at 00:19

1 Answers1

1

As You read example in this link

You would see this:

var connection = mongoose.createConnection("mongodb://localhost/myDatabase");

autoIncrement.initialize(connection);

In fact .connect and .createConnection are different things.

Due to documentation here which says:

Mongoose creates a default connection when you call mongoose.connect().

You can access the default connection using mongoose.connection.

that means mongoose.connect does not return connection and You can get that connection using mongoose.connection.

Solution:

mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true})
        .then(() => {
          console.log('Connected to DB');
        })
        .catch(error => {
          console.error('Connection to DB Failed');
          console.error(error.message);
          process.exit(-1);
        });
autoIncrement.initialize(mongoose.connection);



or You can create a connection as here:

const connection = mongoose.createConnection(process.env.MONGODB_URI);
autoIncrement.initialize(connection);
num8er
  • 18,604
  • 3
  • 43
  • 57