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.
- Is mongoose.connection.db equivalent to the db instance returned from MongoClient.connect ?
- Doesn't mongoClient support promises?
- 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.