Creating users or custom roles in MongoDB on a NodeJS server is not currently possible

I have been attempting to directly create users on my database through our Express server, utilizing MongoDB 3.4 for the backend. Below is the current code snippet from the server:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://mongo:27017/myDb';

const dbvotes = "collection1";
const dbusers = "collection2";


//User functions
app.post('/newUser', function(req, res, db) {

    MongoClient.connect(url, function(err, db){

        //Writing data into the user collection
        db.collection(dbusers).insertOne( {
            "name" : req.body.name,
            "surname" : req.body.surname,
            "username" : username,
            "password" : "pasadmin",
         });

        //Creating the user in the DB
        db.createUser( { 'user': username, 'pwd': "pasadmin", roles: [] });


        db.close();
        });
    console.log("A new user has been added to the database.");
    res.send("User successfully added. Click previous to add another user.");
});

However, there seems to be an issue when trying to insert a new user as although it is created in the user collections, it doesn't register as a user in the database resulting in the error message: TypeError: db.createUser is not a function at /app/app.js:47:6.

I have attempted using db.addUser which is deprecated since Mongo 2.6 and does not work, while db.adminCommand also yields the same error of not being a function. Initially, I struggled with creating custom roles via Node but had to resort to doing it through the Mongo shell. However, adding individual users this way is not feasible.

The commands work perfectly fine in the Mongo shell, leading me to believe that the issue lies in the implementation of MongoDB within the server (using Docker), or perhaps due to limitations with Javascript. Any insights on what might be causing this?

Appreciate any assistance from the community!

Answer №1

In order to correctly execute the command, you should use:

db.addUser( username, password, { roles: [ role ] } );

The value of role needs to be a valid MongoDB role. For more detailed information, refer to the source file. It can also take on the format of an object like

{ role: <string>, db: <string> }
, where 'role' is a MongoDB role and 'db' is the database name.

An alternative method is using db.admin().addUser. This would be preferable if the user requires access to multiple databases or for centralized user management.

However, it's generally not recommended to add system users directly from your application unless it's specifically designed as an administrative tool. Regular "users" should be handled in your own users collection. System users are individuals who have direct database access and should be managed carefully.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

Purge session files that have expired in the session-file store

I have implemented session-file-store to manage sessions in my Node-Express application. With session-file-store, a new file is created for each session, leading to an accumulation of files on the server over time. Is there a method or configuration opti ...

Retrieve the nearest attribute from a radio button when using JQuery on a click event

I have a query regarding the usage of JS / JQuery to extract the data-product-name from a selected radio button, prior to any form submission. Although my attempt at code implementation seems incorrect: return jQuery({{Click Element}}).closest("form" ...

Utilize a method in Vue.js to filter an array within a computed property

I have a question regarding my computed property setup. I want to filter the list of courses displayed when a user clicks a button that triggers the courseFilters() method, showing only non-archived courses. Below is my current computed property implement ...

What is the best way to perform a "redirect" using React following a successful login through passport.js?

Looking for guidance: I'm new to React and have integrated it with passport.js and express. I've successfully logged into the application, but I'm unsure how to set up a redirect. router.post('/login', passport.authenticate(&apo ...

What is the process of connecting a Yarn module to a Docker container in another repository?

I'm currently facing a challenge in linking a module to a Docker container from another repository. To provide some background, I have a container hosting a React application named launch-control-admin. This project relies on a yarn module called @com ...

Effective Ways to Redirect During or After Executing the onClick Function of Button

I am currently working on implementing a feature for my Next.js website. The functionality involves allowing users to create a new group by clicking a button, and then being redirected to an "Invite members" page with the auto-generated group_id included i ...

What is the best approach to integrating AJAX calls with promises in the Angular framework?

I'm facing an issue while using Angular promises with the $q service in my controller. Here's the code snippet: var myController = function ($scope, myService) { $scope.doSomething = function (c, $event) { $event.preventDefault(); ...

What is the correct way to update an empty object within the state using setState?

I'm currently dealing with a state that looks like this: this.state={ angles:{} } I need to know how to use setState on this empty object. Specifically, if I want to add a key and value inside my empty 'angles'. How can I achieve that? Fo ...

Methods for eliminating curly braces from HTTP response in JavaScript before displaying them on a webpage

When utilizing JavaScript to display an HTTP response on the page, it currently shows the message with curly braces like this: {"Result":"SUCCESS"} Is there a way to render the response message on the page without including the curly braces? This is the ...

Removing Embedded Json Element from a Collection in AngularJS HTML

In my JSON Collection, I want to display the Email ID that is marked as IsPreffered = TRUE using AngularJS HTML without using JavaScript. This is my JSON Collection: { "user" : [ { "Name" : "B. Balamanigandan", "Email": [ ...

Database Submission of Newsletter Information

I recently grabbed the following code snippet from a YouTube tutorial (shoutout to pbj746). Everything appears to be functioning correctly except for one crucial issue - the submitted data isn't showing up in the database! I've thoroughly checked ...

Unable to acquire lock for the application "app" in cPanel for Node.js

I encountered an issue while trying to deploy my node.js app. I have created and installed modules using the cPanel interface, but when running the script, I received an error message stating: "Can't acquire lock for app: app." Does anyone have any su ...

What is the process of invoking a JavaScript function from Selenium?

How can I trigger a JavaScript function from Selenium WebDriver when using Firefox? Whenever I am logged into my website, I typically utilize this command in Firebug's Command Editor to launch a file upload application: infoPanel.applicationManager. ...

What could be causing the browser to become unresponsive when making several AJAX requests to the same ASP.NET MVC action at once?

The other day, I posed this query: Why is $.getJSON() causing the browser to block? I initiated six jQuery async ajax requests simultaneously on the same controller action. Each request takes around 10 seconds to complete. Upon tracking and logging re ...

"I'm receiving the error message 'Unable to authenticate user' when attempting to connect to Supabase through the NextJS tutorial. What could be the

Recently, I embarked on a new project using NextJS and Supabase by following the tutorial available at this link. After completing the initial setup by updating the ".env.example" file to ".env.local" with the Supabase credentials, including creating a ne ...

Having trouble uploading a file to multer using supertest while authentication is enabled

Currently, I am utilizing multer for managing file uploads in my express application. Additionally, I have integrated node-sspi for ntlm authentication. When performing a file upload with curl, everything functions smoothly. However, attempting the same o ...

Ways to determine if a web browser is executing javascript code (without altering the javascript on the webpage)

Working on creating a custom PHP client for Selenium, I've encountered an issue with implementing the waitForPageToLoad() function: The problem lies in just checking the document.readyState, as there could be JavaScript scripts running on the page (l ...

Is there a problem with the URI when trying to connect to MongoDB using NPM?

My struggle with connecting to MongoDB (Atlas) has made me feel like I'm losing my mind. The logs are as useful as an anchor on a sinking boat. Here's the situation. Any help would be greatly appreciated. This is what my server.js file looks lik ...

Error encountered while attempting to save user to mongoose due to bcrypt issue

I am currently dedicated to expanding my knowledge in node and react through a tutorial. If you want to check out the repository, here is the link: While making a post request to /api/users/register, I encountered an error that seems to stem from an unde ...