在ExpressJS上使用mongoose运行'node_acl'

Mid*_*der 5 acl mongoose mongodb node.js express

我正在ExpressJS上构建一个应用程序(类似于博客).我正在使用mongoose与MongoDB一起工作.

当我不得不在各种ACL模块之间进行选择时,我决定使用 node_acl.令我困惑的是它使用的是mongodb模块而不是mongoose.

根据ACL GitHub上的文档,它必须以这种方式使用:

// Or Using the mongodb backend
acl = new acl(new acl.mongodbBackend(dbInstance, prefix));
Run Code Online (Sandbox Code Playgroud)

如果我使用mongoose,那么db的实例是什么?

我使用类似的东西:Account = mongoose.model('Account',new Schema({...}));

Val*_*rum 11

在我的头顶,我想你正在寻找这个:

http://mongoosejs.com/docs/api.html#connection_Connection-db

示例(未测试):

var mongoose = require('mongoose'),
    acl = require('acl');

acl = new acl(new acl.mongodbBackend(mongoose.connection.db, 'acl_'));
Run Code Online (Sandbox Code Playgroud)

(这当然是假设你已经使用mongoose.connect()在其他地方初始化了Mongoose.)

  • 我试过这种方式,但我没有成功.ACL集合未出现在我的数据库中,系统无法运行. (2认同)

小智 7

我最近碰巧遇到了这个问题.我在stackoverflow上尝试了很多解决方案但是徒劳无功.最后我找到了问题的原因.只想分享我解决这个问题的经验.通常人们将db config和acl config分开,从而导致此问题.

问题的根源是node.js的本机功能 - 异步.如果您尝试使用以下方式记录连接状态:

console.log(mongoose.connection.readyState);
Run Code Online (Sandbox Code Playgroud)

您将在db.js中找到它,它是1(已连接); 在你的acl.js中,如果你没有在确保mongodb已连接的正确块中制作acl,它将是2(连接).

如果您遵循投票最多和最新的答案,您的代码可能如下所示:

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_'));

});
Run Code Online (Sandbox Code Playgroud)

然后您可能想要设置权限和角色.但请记住在已建立与mongodb的连接的块中进行这些操作.所以最后你的代码应该是这样的:

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();

});
Run Code Online (Sandbox Code Playgroud)