OptimalBits / node_acl

Access control lists for node applications
2.62k stars 369 forks source link

self.db.collection is not a function #281

Open helxsz opened 4 years ago

helxsz commented 4 years ago

i am using ACL module with mongodb, i define some roles and their permissions using the acl.allow() function.

const node_acl = require('acl');
const mongodb = require('mongodb');
let acl = null;
mongodb.connect(config.db.uri, (error, db) => {
 if (error) {
   throw error;
 }
 console.log('connected ..........',config.db.uri,db); // running successfully
 var mongoBackend = new node_acl.mongodbBackend(db, 'acl_', true);
 acl = new node_acl(mongoBackend);
});

I am sure the database is connected, but the code running above gave me an error saying

_Unhandled rejection TypeError: self.db.collection is not a function at /Users/abc/Documents/projects/game/server/node_modules/acl/lib/mongodb-backend.js:120:15 at /Users/abc/Documents/projects/game/server/node_modules/async/dist/async.js:3853:24 at replenish (/Users/abc/Documents/projects/game/server/node_modules/async/dist/async.js:946:17) at /Users/abc/Documents/projects/game/server/node_modules/async/dist/async.js:950:9 at eachOfLimit (/Users/abc/Documents/projects/game/server/node_modules/async/dist/async.js:975:24) at /Users/abc/Documents/projects/game/server/node_modules/async/dist/async.js:980:16 at _parallel (/Users/abc/Documents/projects/game/server/node_modules/async/dist/async.js:3852:5) at Object.series (/Users/abc/Documents/projects/game/server/node_modules/async/dist/async.js:4708:5) at MongoDBBackend.end (/Users/abc/Documents/projects/game/server/node_modules/acl/lib/mongodb-backend.js:36:11) at Acl.allow (/Users/abc/Documents/projects/game/server/nodemodules/acl/lib/acl.js:346:26)

ghaedi1993 commented 4 years ago

i had this issue replace db with mongo.collections.db and its good to go

calvincheng919 commented 3 years ago

Distinctively lack of info out there on this issue. Not sure if you're still dealing with this issue.

Along the same lines as @ghaedi93, you have to access the correct object in mongo version >= 3.0

This is what I ended up with:

var acl = require('acl');
const mongodb = require('mongodb');

const databaseURI = `mongodb://localhost:27017/acldb`;
mongodb.connect(databaseURI, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, database) {
  console.log("Connected successfully to server");
  acl = new acl(new acl.mongodbBackend(database.db('acldb'), '_acl'));

  acl.allow('guest', 'blogs', 'view')
    .then( (result)=> {
      console.log(result);
    })
    .catch( err => {
      console.log(err);
    })

});

If you replace your db in your mongodbBackend function argument with db.db('dbname') it should work