0

I am trying to create mongo users using javascript as part of an installation script.

I would like to know how to validate the return statement of the previous command before proceeding with the next.

For example in the following script,

var db = db.getSiblingDB("admin");
var status = db.createUser({user: "root",
  pwd: "root",
  roles: [
    { role: "root", db: "admin" }
  ]
});

I need to verify if db.createUser succeeded before running further commands.

Is it possible? When I tried to print status, console threw undefined type error.

Thanks in advance.

1 Answer 1

2

I need to verify if db.createUser succeeded before running further commands.

By default, you can rely that this particular command succeeded, if you didn't get any error. If it can't add a user (because user with this name already exists), an error will be raised. Something like this:

2017-03-20T19:17:42.097+0300 E QUERY    [thread1] Error: couldn't add user: User "root@admin" already exists :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.createUser@src/mongo/shell/db.js:1267:15
@(shell):1:14

If you want to be extra sure, look for your newly added user in the output of db.getUsers().

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to validate it from within javascript? Can this mongo level error log be caught in the js?
@Nataraj Have you tried? It should propagate to client side, yes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.