I happened to encounter this issues recently as well. And I tried many many solutions on stackoverflow but in vain. Finally I found the cause of the problem. Just want to share my experience upon resolving this issue. Typically people separate db config and acl config, thus cause this problem.
The source of the problem is the native feature of node.js--async. If you tried to log the connection status using:
console.log(mongoose.connection.readyState);
You will find in your db.js, it is 1(connected); while in your acl.js, it would be 2(connecting) if you do not make acl in the proper block that ensures mongodb is already connected.
If you follow the most voted and latest answer, your code may look like this:
var acl = require('acl');
var mongoose = require('../model/db');
mongoose.connection.on('connected', function(error){
if (error) throw error;
//you must set up the db when mongoose is connected or your will not be able to write any document into it
acl = new acl(new acl.mongodbBackend(mongoose.connection.db, 'acl_'));
});
And then you may want to set your permissions and roles. But remember to make these in the block where the connection to mongodb is already built. So finally your code should look like this:
var acl = require('acl');
var mongoose = require('../model/db');
mongoose.connection.on('connected', function(error){
if (error) throw error;
//you must set up the db when mongoose is connected or your will not be able to write any document into it
acl = new acl(new acl.mongodbBackend(mongoose.connection.db, 'acl_'));
//Do acl.allow('role', ['resources'], ['actions'] here
initACLPermissions();
//Do acl.addUserRolss('id', 'role') here
initACLRoles();
});