Search code examples
javascriptmongodbexpresscreateuser

Impossible to create users (or custom-based roles) in Mongo on server NodeJS


I am trying to create users on my database directly from our Express server, using Mongo 3.4 for the database. Here is the code for the server for now:

var express = require('express');

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

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

var dbvotes = "collection1";
var dbusers = "collection2";


//Functions for users
app.post('/newUser', function(req, res, db) {

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

        //Ecriture dans la base user
        db.collection(dbusers).insertOne( {
            "name" : req.body.name,
            "surname" : req.body.surname,
            "username" : username,
            "password" : "pasadmin",
         });

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


        db.close();
        });
    console.log("Inserted a new user in the database.");
    res.send("User added. Click precedent to add a new user.");
});

However, whenever the client tries to insert a new user, it is effectively created in the user collections, but not as a user of the database as I get the following error: TypeError: db.createUser is not a function web_1 | at /app/app.js:47:6.

I have tried to user db.addUser instead, however, this is deprecated since Mongo 2.6 and not working either, and db.adminCommand serves the same error, db.adminCommand is not a function. Before that, I struggled to create custom roles in the database with Node and decided to do it via the Mongo shell as well, but it's not an option when it comes to adding user 1 by 1 in the database.

When I use these functions in the Mongo shell, the commands are working, so I suppose it comes from the way I implemented Mongo within the server (via Docker), or due to some limitations with Javascript. Any idea what could it be?

Thanks in advance to the community!


Solution

  • The proper command would be:

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

    Where role is some MongoDB role. More info can be found from the source file. It can also be an object in the formation of { role: <string>, db: <string> }, where role is a MongoDB role and db is the string name of the database.

    You can also use db.admin().addUser. This would be the logical choice if the user has access to multiple databases or you want a central location of your users.

    However, I can't imagine it's a good idea to add system users from your application unless you're developing an actual administrative tool. Normal "users" added to a database would be in your own users collection. A system user is someone who has direct access to your database.