Search code examples
c++mongodbmongo-cxx-drivercreateuser

CreateUser fails using mongocxx 3.1.1 C++


Using the MongoDB server 3.4.4 on Windows 10, the following command works just fine:

db.createUser(  
{  
    user: "Billy",  
    pwd : "123456",  
    roles :   
    [  
        { role: "userAdmin", db : "biolomics_index" },  
        { role: "dbAdmin", db : "biolomics_index" },  
        { role: "readWrite", db : "biolomics_index" }  
    ]  
}  

Running the same command with the mongocxx 3.1.1 C++ drivers fails:

db.run_command(document{} << "createUser" << open_document <<  
    "user" << "Billy" <<  
    "pwd" << "123456" <<  
    "roles" << open_array <<  
        open_document << "role" << "userAdmin" << "db" << "biolomics_index" << close_document <<  
        open_document << "role" << "dbAdmin" << "db" << "biolomics_index" << close_document <<  
        open_document << "role" << "readWrite" << "db" << "biolomics_index" << close_document << 
    close_array << close_document <<  
    finalize);  

with the error:

"createUser" had the wrong type. Expected string, found object: generic server error.

I can't find the syntax to generate the correct document. Any idea?


Solution

  • According to the createUser documentation, the username should be placed as a value of createUser instead of user field. Change your code to:

    db.run_command(document{} << 
        "createUser" << "Billy" <<  
        "pwd" << "123456" <<  
        "roles" << open_array <<  
            open_document << "role" << "userAdmin" << "db" << "biolomics_index" << close_document <<  
            open_document << "role" << "dbAdmin" << "db" << "biolomics_index" << close_document <<  
            open_document << "role" << "readWrite" << "db" << "biolomics_index" << close_document << 
        close_array <<  
    finalize);  
    

    NOTE:
    As mentioned by Saghm in the comment, the MongoDB shell helpers are not exactly the same as the "run command" equivalents in the drivers. You can use the shell's db.runCommand if you want to try out things with the same BSON that the driver requires in database::run_command.

    1. Consults Database Commands Manual for available commands and parameters from within the driver.
    2. The mongo Shell Methods Documentation describes methods, commands and parameters for interacting with the MongoDB server through mongo shell.