Nick Grealy
Nick Grealy

Reputation: 25864

MongoDB NodeJS > db.createRole is not a function

I'm using the "Node.js MongoDB Driver API", and I was hoping to convert my database initialisation scripts to NodeJS.

I can't find any admin commands (e.g. db.createRole(), db.grantPrivilegesToRole()). Do these functions exist somewhere else? OR is there some alternative workaround I can use? (e.g. runCommand)

Here is the full code snippet.

db_test.js

const MongoClient = require('mongodb').MongoClient

MongoClient.connect('mongodb://admin:password@localhost:27017/admin')
  .then(client => client.db('admin').admin())
  .then(db => {
    return db.createRole({
      role: 'SOME_ROLE',
      privileges: [],
      roles: []
    })
  })
  .then(() => {
    console.log('Success!')
    process.exit(0)
  })
  .catch(err => {
    console.log('Error! - ' + err.message)
    process.exit(99)
  })

Output:

Error! - db.createRole is not a function

NodeJS Library: "mongodb": "3.1.4"

Docker Server: image: mongo:3.4.2

Disclaimer: I've also asked this question in GoogleGroups.

Upvotes: 0

Views: 504

Answers (2)

Sandeep
Sandeep

Reputation: 431

db.createRole is not a function. Try doing it like this:

db.command( { createRole: 'SOME_ROLE', privileges: [], roles: [] } )

References:

Upvotes: 2

You got error because db is not defined in this line : .then(dbAdmin => db.createRole(...))

Try like this :

MongoClient.connect('mongodb://admin:password@localhost:27017/admin',(err,db) =>{

    if (err) return console.log(err);

    db.createRole(...)

});

Upvotes: 0

Related Questions