2016-09-06 52 views
0

我想定義一個自定義的Mongo shell命令。鑑於.mongorc.js是象下面這樣:MongoDB:在.mongorc.js中定義的自定義命令

var dbuc; 

(function() { 
    dbuc = (function() { 
     return db.getName().toUpperCase(); 
    })(); 
})(); 

我得到正確的大寫的名稱初始數據庫,但是當我切換到其他數據庫,我仍然得到初始數據庫,而不是當前的名字。

> db 
test 
> dbuc 
TEST 

> use otherbase 

> db 
otherbase 
> dbuc 
TEST 

我看到.mongorc.js之前mongo運行運行,這就是爲什麼dbuc變量分配的初始數據庫的價值 - 測試。但我想知道如何獲得當前數據庫的名稱,無論我打開哪個基地。

回答

0

有幾點需要注意:

  • 在蒙戈外殼,typeof db是一個JavaScript對象和typeof dbuc是字符串。
  • 我相信,在您的代碼中,dbuc值被分配一次,並且在調用use時不會改變。
  • useshellHelper函數(在mongo shell中輸入shellHelper.use)。它用新返回的數據庫對象重新分配變量db

解決方案之一,爲dbuc工作,就是下面的代碼添加到.mongorc.js

//The first time mongo shell loads, assign the value of dbuc. 
dbuc = db.getName().toUpperCase(); 

shellHelper.use = function (dbname) { 
    var s = "" + dbname; 
     if (s == "") { 
      print("bad use parameter"); 
      return; 
     } 
db = db.getMongo().getDB(dbname); 

//After new assignment extract and assign upper case of newly assgined db name to dbuc. 
dbuc = db.getName().toUpperCase(); 

print("switched to db " + db.getName()); 

} 
+0

THX,我的避風港」 T在文檔中遇到'shellHelper'遠。 –