2017-07-15 54 views
0

我已經在我的MongoDB中設置了auth,如here所述。最初,在我的項目,我訪問使用使用貓鼬連接到多個數據庫時進行身份驗證

let url = "mongodb://localhost:27017/firstdb"; 
let options = { 
    server:{ 
     socketOptions:{ 
      keepAlive:120 
     } 
    }, 
    user:"username1", 
    pass:"mypassword1" 
}; 
mongoose.connect(url,options,callback); 

用戶與usernamemypassword是在firstdb創建本身給它readWrite燙髮單個數據庫說,從貓鼬firstdb。我在使用我的管理員用戶登錄時執行了此操作。

事情進展順利。然後我有連接到第二個數據庫的要求。所以我改變了我的代碼,這樣

let url1 = "mongodb://localhost:27017/firstdb"; 
let options1 = { 
    server:{ 
     socketOptions:{ 
      keepAlive:120 
     } 
    }, 
    user:"username1", 
    pass:"mypassword1", 
    auth:{ 
     authdb:"firstdb" 
    } 
}; 
let connection1 = mongoose.createConnection(url1,options1); 

let url2 = "mongodb://localhost:27017/seconddb"; 
let options2 = { 
    server:{ 
     socketOptions:{ 
      keepAlive:120 
     } 
    }, 
    user:"username2", 
    pass:"mypassword2", 
    auth:{ 
     authdb:"seconddb" 
    } 
}; 
let connection2 = mongoose.createConnection(url2,options2); 

這一次,我創建的用戶username2seconddb數據庫的方式相同。但是現在貓鼬無法執行任何操作,並且因Not authorized to execute command而失敗。我可以通過mongo shell訪問數據庫。我也在我的本地系統中啓用了沒有啓用mongodb auth的代碼,它在那裏工作正常。請幫忙

回答

0

所以,在盲人身邊射擊之後,發現了一些可行的東西。 使用用戶名和密碼在URL本身就像

let connection1 = mongoose.createConnection("mongodb://username1:[email protected]:27017/firstdb"); 

不過,我想知道爲什麼傳遞參數的選擇不工作。

相關問題