retrieve mongoDB driver db from mongoose

Viewed 12069

I am designing a module provides a constructor function that takes in a mongo db instance as its parameter. In my application I am trying to test this using mongoose. Since mongoose was built on mongoDB driver module, I am assuming that there is a way to retrieve the db driver object from the mongoose module.

I have a function that is failing but I am unsure to the reason why.

Update

Below is the code from my module

//authorizer.js
function Authorizer(mongoDBCon, userOptions){
    this.db = mongoDBCon;
    this.authorize = authorize;
    this.assignOwner = assignOwner;
    this.setUserPermission = setUserPermission;
    this.setRolePermission = setRolePermission;
    this.retrieveUserPermission = retrieveUserPermission;
    this.setRolePermission = setRolePermission;

    let defaultOptions = {
        unauthorizedHandler: (next)=>{
            let error = new Error('user has performed an unauthorized action');
            error.status = 401;
            next(error);
        },
        userAuthCollection: 'user_authorization',
        roleAuthCollection: 'role_authorization',

    }

    this.options = _.assign({},defaultOptions,userOptions);
}

function setRolePermission(role, resource, permissions) {
    let document = {
        role: role,
        resource: resource,
        permissions: permissions,
    };

    //add the document only if the role permission is not found
    let collection = this.db.collection(this.options.roleAuthCollection);
    collection.findOne(document)
        .then((result)=>console.log('in here')) //------> not printing :(
        .catch(e=>{console.log(e)});
}

It needs to be imported/required in another file to configure

//authorizerConfig
let mongoose = require('mongoose');
let Authorizer = require('util/authorization/authorization');

let authorizer = new Authorizer(mongoose.connection.db);

//set admin role permissions
authorizer.setRolePermission('admin', 'users', '*');
authorizer.setRolePermission('admin', 'postings', '*');

module.exports = authorizer;

file with connection to mongo

//app.js
// Set up and connect to MongoDB:
const mongoose = require('mongoose');
mongoose.Promise = Promise;
mongoose.connect(process.env.MONGODB_URI);//MONGODB_URI=localhost:27017/house_db

I now am not seeing a log that I was hoping to see in the then() method.

  1. Is mongoose.connection.db equivalent to the db instance returned from MongoClient.connect ?
  2. Doesn't mongoClient support promises?
  3. Can you help solve my issue?

Answer: @Neil Lunn has provided me with the answer. To sum up, mongoose.connection.db is equivalent to the db returned from MongoClient.connect. Also, I had an error because I was querying the db before it has established a connection.

3 Answers

Note that this seems to have changed at some point and in v5 I can access the db like this:

const res = await mongoose.connect(...);
const { db } = mongoose.connection;
const result = await db.collection('test').find().toArray();

Use the connection object to retrieve the MongoDB driver instance.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testdb', function (err){
    if (err) throw err;
    let db = mongoose.connection.db; // <-- This is your MongoDB driver instance.
});
Related