Is there a way to check if a database exists in Mongo from the Node.js driver?
我发现很难从Node.js驱动程序中找到一种方法来查看MongoDB中是否存在数据库的方法。 Node.js驱动程序似乎没有方法来检查数据库是否存在。
例如,以下内容不会引发错误:
1 2 3 4 5 6 7 8 9 10 | 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); }); }); |
结果将是这样的对象:
1 2 3 4 5 6 7 8 9 10 11 | { db: 'databaseThatDoesntExist', collections: 0, objects: 0, avgObjSize: 0, dataSize: 0, storageSize: 0, numExtents: 0, indexes: 0, indexSize: 0, fileSize: 0, ok: 1 } |
您能否通过Node.js驱动程序检查MongoDB中是否存在数据库? MongoDB中甚至存在数据库的概念吗?引用不存在的数据库只是引用没有集合的数据库吗?
蒙哥,你为什么不能只抛出一个错误!我喜欢我的代码
检查
如果服务器已启用授权,则您将需要适当的权限。
判断数据库是否存在的最简单方法是从她将要使用的mongo中获取信息。要列出所有可用的数据库,请在Mongo Shell中输入以下内容。
1 | show dbs |
要列出您当前正在使用的数据库,请输入:
1 | db |
要显式选择数据库,请输入:
1 | use <database> |