Search code examples
node.jsmongodbmongoose

Create a mongoDB Database User from NodeJS


i am trying to create a new User from my mongo Database from Nodejs. I know you can create a user via the cli like that:

db.createUser({
  user: 'USERNAME',
  pwd: passwordPrompt(),
  roles: [{
    role: 'readWrite',
    db: 'DATABASE'
  }]
})

But that is not what i am looking for, is there any way to create a User for the Database from within nodejs? Is there any libary to do such a thing or is there an api to create a new User?


Solution

  • In MongoDb node driver, the createUser is not available, instead you will have to use addUser

    db.addUser('username', 'password' , {
     roles
    })
    

    You can refer to this api documentation provided by the official MongoDb node driver.

    https://mongodb.github.io/node-mongodb-native/4.1/classes/Db.html#addUser https://mongodb.github.io/node-mongodb-native/4.1/interfaces/AddUserOptions.html