What methods exist for generating users in mongodb through a script?

Currently, I am in the process of configuring mongodb, and our servers are managed through puppet.

While I have successfully set up most components as required, I still need to create a user within the mongo database.

I am familiar with how to accomplish this task using the mongo shell by executing javascript commands such as:

db.addUser("username", "password"[, readOnly])

However, what eludes me is finding a concrete example demonstrating how to execute this in javascript. My ultimate objective is to add a user from the command line, preferably through a shell script.

If someone could provide:

a) references to reliable examples illustrating the use of javascript with MongoDB, and

b) guidance on how to achieve this through the command line?

Answer №1

When using MongoDB's cli, it provides guidance on how to utilize a JavaScript file

$ mongo --help
MongoDB shell version: 2.0.3
usage: mongo [options] [db address] [file names (ending in .js)]
...

usage: mongo [options] [db address] [file names (ending in .js)]

Here is an example:

$ echo 'db.addUser("guest", "passwordForGuest", true);' > file.js
$ mongo mydb file.js
MongoDB shell version: 2.0.3
connecting to: mydb
{ "n" : 0, "connectionId" : 1, "err" : null, "ok" : 1 }
{
    "user" : "guest",
    "readOnly" : true,
    "pwd" : "b90ba46d452e5b5ecec64cb64ac5fd90",
    "_id" : ObjectId("4fbea2b013aacb728754fe10")
}

Update:
db.addUser deprecated since 2.6
https://docs.mongodb.com/v2.6/reference/method/db.addUser/

Now, use db.createUser instead:

// file.js
db.createUser(
  {
    user: "guest",
    pwd: "passwordForGuest",
    roles: [ { role: "read", db: "mydb" } ]
  }
)

$ mongo mydb file.js

Answer №2

Check out this sleek and straightforward alternative:

echo 'db.createUser({user:"<username>", pwd:"<password>", roles:["readWrite"]});' | mongo <database>

Verified to work with MongoDB version 2.4.8

Answer №3

Although AD7six has addressed a similar issue, I encountered a scenario where I was able to access a user with database authentication 'test'.
To resolve this, I included a command before creating the user to specify the authentication database.

db = db.getSiblingDB('myCustomDatabase');
db.createUser(
 {
   user: "myNewUser",
   pwd: "mySecurePwd",
   roles: [
    { role: "readWrite", db: "myCustomDatabase" }
   ]
 }
);

Note that the authentication database may differ from the database assigned to the user. Using the JavaScript command "getSiblingDB(dataBase)" serves as an alternative to the Shell command "use dataBase".

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

The Xero Node OAuth Authorize Callback URL is malfunctioning after granting access

When utilizing the xero-node library to produce a Request Token using the getRequestToken function, the URL provided does not automatically redirect the user to the designated callback address specified in the configuration. Instead, a screen displaying a ...

Guide to utilizing Ajax request for a targeted controller method?

I am attempting to utilize Ajax to refresh data from a database. However, the Ajax script is not triggering the controller action specified in the url:. Here is the code snippet for my Ajax functionality: function selectFieldChanged(id){ $.ajax({ ...

Creating responsive HTML page text and table with the use of JavaScript

Trying to create a responsive webpage has been a bit challenging. I experimented with height,style.height, style.OffsetHeight, etc. but still struggling to dynamically make a square table. Although the code below changes the height, the table's width ...

Ways to troubleshoot a validation error when the user selects the captcha

I have incorporated a captcha into my asp.net MVC core web application using the following code: <div class="form-group"> <div class="col-md-2"></div> <div class=" ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

Trouble with AJAX page loading and history.pushState functionality following navigation away from the site

My website utilizes XMLHttpRequests to fetch specific parts of webpages upon a user clicking a link. Below is the relevant code snippet: function requestPage(url, push) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { ...

Encountering an error "[$rootScope:inprog]" while using Angular select with ngModel

I'm still learning my way around Angular, but I have a basic understanding. Right now, I'm working on assigning access points to a building using a <select> element. I've created a simple controller for this task, but it's not fun ...

Utilizing DataLoader in tandem with Mongoose: A comprehensive guide

I am currently working on implementing DataLoader with Mongoose for the following use case: export const PurchaseOrderType = new GraphQLObjectType({ name: "PurchaseOrder", description: "PurchaseOrder", interfaces: () => [NodeInterface], ...

You are unable to establish headers once they have already been sent to the client, as indicated by the error

Github : https://github.com/UJJWAL2001/Pro-Shop/tree/main/backend My current objective is to implement JWT token for securing my routes using the middleware provided below import jwt from 'jsonwebtoken' import User from '../models/userModel ...

Unusual shift in behavior - <input> on Windows 8.1

Our application is a unique HTML5/WinJS Google Talk app tailored for Windows 8 users. Within our app, we utilize a textarea for chat input with a predefined maximum height. We have coded the height to automatically adjust to the maximum limit once reached. ...

What is the process for resolving arguments in UI-Router's resolve function?

There seems to be a gap in my understanding of UI-Router and angular's documentation, so forgive me if this seems naive, but here goes: On http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider, there is an example resolve fu ...

Mastering the art of simulating Sequelize model methods in Node.js

Recently, I have encountered some difficulties trying to mock a database in my side project while writing junits. Can anyone lend me a hand here? Here's the scenario: If you need to take a look at the source code, it's available here - https://g ...

Having difficulty displaying TIFF images and incorporating them into a Fabric Object

I have gone through the tutorials available at: and also familiarized myself with the Fabric Objects documentation. While I was successful in loading JPG and PNG images onto the canvas, my current project requires me to load TIFF images and apply filters ...

Trying to bring in components from directories above

I'm currently facing an issue with importing components from a parent directory into my project. My goal is to be able to use these components across multiple projects, which seems like the most straightforward approach. However, when I attempt this, ...

Tips on flipping a texture in Three.js along the horizontal axis

Currently developing a 360 viewer with textures contained within a cylinder. Encountering an issue where textures are appearing horizontally inverted. Although I am aware of the texture.flipY option, I have not been able to locate a texture.flipX function ...

A guide on utilizing nodejs to automatically open the default browser and direct it to a specific web address

I am currently developing a program using Node.js. One of the features I aim to implement is the ability to launch the default web browser and direct it to a particular URL. I want this functionality to be compatible across Windows, Mac, and Linux operat ...

Displaying different elements using an anchor <a> tag

Within this example, I've created two functional components that mimic separate pages with differently colored <div> boxes. const Home = () => <div style={{background:'red', height: 100, width: 100}}></div>; const ...

Incorporate code into the layout using Express, Jade, and templates

Exploring a Express site with Node.JS In my layout file, it currently looks something like this: html title foo body!= body After some research, I have discovered that the template output is placed into a variable called body, which is then added to ...

Implementing CORS for a custom route in Sails.js - a complete guide

I am experiencing an issue with my Angular 1.x app that calls APIs in my Sails.js app. Every time I attempt to make API calls from the Angular app, I encounter the following error - XMLHttpRequest cannot load <a href="http://localhost:1337/portal/login ...

What are some recommended strategies for managing collection relationships within a REST API design?

Welcome to my first query in this forum! I am currently working on an Android messaging application with a Node.js Express backend that is supported by a MongoDB database. At the moment, I have two collection models: User and Message. The message schema i ...