MongoDB Nodejs driver doesn't support creating new users

I’m trying to create new users via MongoDB nodejs driver but MongoDB seems to not have any function to support that. Any alternative way to create an user from a nodejs API? Thanks!

Hi @Thanh_D_o_Nguy_n ,

Welcome to the MongoDB community.

I assume you’re referring to create MongoDB Database user via Mongoose / NodeJs driver. Which I think is not possible because Creating users, assigning them roles are server side and not application or driver side.

If you’re using MongoDB Atlas, You can explore MongoDB Atlas Admin API

If you’re using Self hosted setup of MongoDB, Then you will need to either use Mongo Shell to create Mongo user or a shell script or configuration automation script with Ansible.

Feel free to share any further questions you shall have.


1 Like

Dear @viraj_thakrar

Thank you for your response!

For people who are interested in this topic, I found a solution using “child_process”, a package from npm to run mongosh from my nodejs server. This is the source code:

For node-js you would want to use command from Admin as it is recommended that all users are created within the admin database, although a user can be scoped to a particular database.

User Management Commands are what you will be using with the command method.

The user executing these commands will need userAdmin permissions, effectively making this a superuser role on the database or the cluster(if granted on admin database). For this reason it is not advised to run general application code with this type of account. If you are writing privileged code to only manage users this may be appropriate usage.

For MongoDB Atlas as @viraj_thakrar mentions the MongoDB Atlas Admin API is your raw api access.
There are other Infrastructure as code options for Terraform and AWS Cloud formation. But if you are interested managing Atlas(and database users) on Atlas on AWS in Node JS then the MongoDB Atlas AWS CDK will be of interest.