I am building an application on ExpressJS (similar to a blog). I am using mongoose for working with MongoDB.
I came to the point when I had to choose between various ACL modules, and decided to go with node_acl. What confuses me is that it is using mongodb modules instead of mongoose.
According to the docs on the ACL GitHub it has to be used this way:
// Or Using the mongodb backend
acl = new acl(new acl.mongodbBackend(dbInstance, prefix));
What would be an instance of db if I'm using mongoose?
I use something like: Account = mongoose.model('Account', new Schema({ ... }));
Off the top of my head, I think you are looking for this:
http://mongoosejs.com/docs/api.html#connection_Connection-db
Example (not tested):
var mongoose = require('mongoose'),
acl = require('acl');
acl = new acl(new acl.mongodbBackend(mongoose.connection.db, 'acl_'));
(This is of course assuming you have initialized Mongoose elsewhere with mongoose.connect().)
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With