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

Using AJAX asynchronously in JavaScript commands synchronization

After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary f ...

Disregarding text within an express route

I am currently working with the following routes: app.get('/blah/query.json', doSomething); app.get('/blah/:id.:format', doSomethingElse); At the moment, both routes are being triggered so that route one (query.json) is called first f ...

make the chosen text appear on Internet Explorer

1 How to insert text into a text box using code? 2 Moving the caret to the end of the text. 3 Ensuring the caret is visible by scrolling the text box content. 4 Programmatically selecting specific text in a textbox. 5 **How to make selected text visible?** ...

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Techniques for animating background image using jQuery

Hello there! I'm currently experimenting with animating a background image using jQuery. Despite following a tutorial, I haven't been successful in getting my test page to work as intended. The blue Facebook icon displays, but it doesn't ani ...

Simply tap on the image to include it in the HTML5 Canvas drawing

Currently, I am in the process of drawing a circle onto my html5 canvas as shown in the code snippet below: <!DOCTYPE HTML> <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> &l ...

The HTML elements in my JSX code seem to constantly shift around whenever I resize my webpage

Using react.js, I'm currently developing a website that appears like this before resizing: pre-resize_screenshot_website However, upon vertical or diagonal resizing, the layout becomes distorted especially in the 'availability search bar' ...

Tips for sorting/merging/consolidating data in Angular

Take a look at this code snippet: rowData = [ [ '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2018-12-10 08:00:00' ...

What are the steps for combining AngularJS with Java JAAS authentication system?

My web application combines AngularJS on the frontend with Java on the backend. Angular communicates with the Java backend through Restful webservices exchanging JSON data over HTTP. I am in need of developing an authentication mechanism for this app and I ...

The `user-select: none` property displays distinct behavior in Safari

My Goal I am in the process of creating an input-like content editable div. The idea is to click on tags outside the div and insert them inside the div while still being able to type around these tags. The Issue and Reproduction Steps To prevent tag but ...

Pagination with React Material UI is a user-friendly and visually

Requirement Within the Material UI framework, I need to implement pagination functionality by clicking on the page numbers (e.g., 1, 2) to make an API call with a limit of 10 and an offset incrementing from 10 after the initial call. https://i.stack.imgur. ...

Display the variance in values present in an array using Node.js

I am facing a challenge and need help with printing arrays that contain both same and different values. I want to compare two arrays and print the values that are present in both arrays in one array, while also creating another array for the differing val ...

When trying to access data within objects using JSON iteration, it may lead to encountering an issue of reading a

Attempting to retrieve specific data from a JSON file obtained from a website has proven challenging. While iterating through the collection of objects, undefined values are constantly encountered. Unfortunately, if the JSON is poorly structured, modificat ...

Placing a MongoDB query results in an increase of roughly 120MB in the total JS heap size

I'm puzzled by the fact that the heap size increases when I include a MongoDB database query in a function within my controller. Here is the code for my router: import { Router } from "express"; import profileController from '../contro ...

Issue with Angular4 select in dropdown not able to trigger onChange event

I am new to working with Angular 4 and I am currently in the process of building something. In my project, I have multiple components, one of which contains the following HTML code: <div class="row" style="border:1px solid black;"> <br> <d ...

When a node sends a request to an endpoint, it receives a response from

In my project, I have a file named "forms.routes.js" which contains a variety of endpoints using router.get, router.post, router.put, and router.delete. Interestingly, when I try to access the 16th endpoint in the list: localhost:3000/v2/forms/:domain/co ...

Extracting information from JSON using arrays

I'm facing a bit of a challenge with this one. I've been trying to use jQuery on my website to update an element. It works perfectly fine without using an array of data in JSON, but as soon as I introduce an array of data, it stops functioning. I ...

What are the steps to create parallel curves in three.js for road markings?

My goal is to create parallel curved lines that run alongside each other. However, when I try to adjust their positions in one axis, the outcome is not what I expected. The code I am using is fairly simple - it involves a bezier curve as the central path ...

Can anyone figure out why this code is not functioning properly? It seems to be targeting the body element and all of

Currently, I am utilizing jqtouch to create a mobile website. In addition to this, I am incorporating a gallery image slider into the website. However, I have encountered an issue where the images do not display when placed between <div id="project_name ...

The div element is overflowing beyond the available space

I have already searched for a solution to this question, but despite trying everything, I have not been able to find one. Therefore, I am asking again, my apologies :-). My challenge is to make a row fill all the remaining screen space on the page, but no ...