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!