CreateUser 使用 mongocxx 3.1.1 C++ 失败

CreateUser fails using mongocxx 3.1.1 C++

在 Windows 10 上使用 MongoDB 服务器 3.4.4,以下命令工作正常:

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

运行 使用 mongocxx 3.1.1 C++ 驱动程序的相同命令失败:

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);  

错误:

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

我找不到生成正确文档的语法。有什么想法吗?

根据 createUser documentation,用户名应作为值 createUser 而不是 user 字段。将您的代码更改为:

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);  

注意:
正如 Saghm 在评论中提到的,MongoDB shell 助手与驱动程序中的 "run command" 等价物并不完全相同。如果您想尝试使用 database::run_command 中驱动程序所需的相同 BSON,您可以使用 shell 的 db.runCommand

  1. 从驱动程序中查询 Database Commands Manual 以获得可用的命令和参数。
  2. mongo Shell Methods Documentation 描述了通过 mongo shell.
  3. 与 MongoDB 服务器交互的方法、命令和参数