2015-05-02 46 views
3

我發現令人驚訝的是很難看到從Node.js驅動程序中查找MongoDB中是否存在數據庫的方法。有似乎是沒有方法在Node.js驅動程序來檢查數據庫是否存在。有沒有辦法通過Node.js驅動程序檢查Mongo中是否存在數據庫?

例如,下列不引發錯誤:

var mongo = require('mongodb').MongoClient; 

mongo.connect({ 'mongodb://localhost:27017/databaseThatDoesntExists }, function (err, db) { 
    // There is no error 
    if (err) console.log(err); 
    // Let's get some stats on a database that doesn't exist 
    db.statsAsync(function (err, result) { 
     console.log(result); 
    }); 
}); 

結果會是這樣一個對象:

{ db: 'databaseThatDoesntExist', 
    collections: 0, 
    objects: 0, 
    avgObjSize: 0, 
    dataSize: 0, 
    storageSize: 0, 
    numExtents: 0, 
    indexes: 0, 
    indexSize: 0, 
    fileSize: 0, 
    ok: 1 } 

你可以檢查看是否有數據庫MongoDB中存在形式Node.js驅動程序? MongoDB中是否存在數據庫的概念?引用不存在的數據庫只引用沒有集合的數據庫?

Mongo,爲什麼你不能只是拋出一個錯誤!我喜歡當我的代碼throws錯誤!

+0

可能的重複http://stackoverflow.com/questions/7049722/check-if-mongodb-database-exists? –

+0

更好的與Node.js驅動程序http://stackoverflow.com/questions/16571021/how-to-list-all-mongodb-databases-in-node-js –

+1

如何在訪問任何集合時停止自動數據庫創建? – rajeshpanwar

回答

2

判斷數據庫是否存在的最簡單方法是從mongo她會。要列出所有可用的數據庫,請在Mongo shell中輸入以下內容。

show dbs 

要列出你目前正在使用的數據庫,輸入:

db 

明確選擇一個數據庫,輸入:

use <database> 
+0

感謝您的回覆。我確實想從Node.js驅動程序中完成。我更新了我的問題以反映這一點。 –

相關問題