Mongoose: "Cannot read property 'collection' of undefined"

Created on 28 Jun 2018  路  4Comments  路  Source: Automattic/mongoose


I got this issue after using the latest version 5.1.7
Do you want to request a feature or report a bug?
bug
What is the current behavior?
the connection.db is undefined in the latest version. I tried a couple of versions. The bug is not existing in the old version 4.11.3, which I was previously using
If the current behavior is a bug, please provide the steps to reproduce.

I am using the connection.db to connect an acl module. But when I checked with breakpoints the connection.db is undefined. I tried the older version of mongoose i.e before 5. and it works fine.
What is the expected behavior?
The connection.db should return a db object.
Please mention your node.js, mongoose and MongoDB version.
node: v10.4.0
mongoose: v5.1.7
mongod : 3.6

can't reproduce

Most helpful comment

I was having this same issue. It looks like you can just do this now:

mongoose.connection.collection('someCollection');

All 4 comments

I was having this same issue. It looks like you can just do this now:

mongoose.connection.collection('someCollection');

I cannot do that because in my case the collection name is dynamic.. and is used by another acl module which handles the creation and manipulation of collections

@suprithwork can you share a code sample that shows connection.db being undefined? I can speculate about why you're experiencing this, but reproducible code is preferred.

Here is an example showing connection.db exists in both versions 4 and 5:

6631.js

#!/usr/bin/env node
'use strict';

const mongoose = require('mongoose');
const usingMongoose4 = (mongoose.version.charAt(0) === '4');
let opts = {};

if (usingMongoose4){
  opts.useMongoClient = true;
  mongoose.Promise = global.Promise;
}

async function run() {
  await mongoose.connect('mongodb://localhost/gh-6631', opts);
  const conn = mongoose.connection;
  console.log(`mongoose version ${mongoose.version}, conn.db === ${typeof conn.db}`);
  (usingMongoose4) ? mongoose.disconnect() : conn.close();
}

run();

Output on @4.11.3

issues: ./6631.js
mongoose version 4.11.3, conn.db === object
issues:

Output on @5.1.7

issues: ./6631.js
mongoose version 5.1.7, conn.db === object
issues:

mongoose.connection.collection('someCollection') saved me for my case.
I was using mongoose.connection.db.collection('someCollection') instead, with the error TypeError: Cannot read property 'collection' of undefined

Was this page helpful?
0 / 5 - 0 ratings