0

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?

1
  • Do you have any Node.js code at all? Commented Oct 9, 2021 at 13:33

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Sure, let me know if this works or not.
1
root@491f9c020125: mongosh mongodb://user1:user1_password@localhost/test 
Current Mongosh Log ID: 666157fd1f466aa659a26a12
Connecting to:          mongodb://<credentials>@localhost/test?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.6
MongoServerError: Authentication failed.
root@491f9c020125:
import {Auth, MongoClient} from 'mongodb';

const uri = 'mongodb://localhost:27017';
const user: Auth = {username: 'mongoose', password: 'secretpass'}; // admin user
const client = new MongoClient(uri, {auth: user});

// create new database
async function createDatabase(client: MongoClient, dbName: string, newUser: Auth) {
    const db = client.db(dbName);

    await db.command({
        createUser: newUser.username,
        pwd: newUser.password,
        roles: [{role: 'readWrite', db: dbName}],
    });

    client.close();
}

createDatabase(client, 'test', {username: 'user1', password: 'user1_password'});
root@491f9c020125: mongosh mongodb://user1:user1_password@localhost/test
Current Mongosh Log ID: 666158b8f7b7469abba26a12
Connecting to:          mongodb://<credentials>@localhost/test?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.2.6
Using MongoDB:          7.0.11
Using Mongosh:          2.2.6

For mongosh info see: https://docs.mongodb.com/mongodb-shell/

test> 

1 Comment

Thanks. This works for the mongodb official driver v6+

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.