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