有没有一种方法可以通过Node.js驱动程序检查Mongo中是否存在数据库? [英] Is there a way to check if a database exists in Mongo from the Node.js driver?
问题描述
我发现很难找到一种从Node.js驱动程序中查看数据库是否存在于MongoDB中的方法. 似乎在Node.js驱动程序中没有检查数据库是否存在的方法.
I'm finding it surprisingly difficult to see find a way to see if a database exists or not in MongoDB from the Node.js driver. There seems to be no method in the Node.js driver to check if a database exists.
例如,以下内容不会引发错误:
For example, the following doesn't throw an error:
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 }
您能否通过Node.js驱动程序检查MongoDB中是否存在数据库? MongoDB中甚至存在数据库的概念吗?引用不存在的数据库只是引用没有集合的数据库吗?
Can you check to see if a database exists in MongoDB form the Node.js driver? Is there even a concept of a database existing in MongoDB? Is referencing a database that doesn't exist just referencing a database with no collections?
蒙哥,你为什么不能只抛出一个错误!我喜欢我的代码throws
错误!
Mongo, why can't you just throw an error! I like when my code throws
errors!
推荐答案
检查是否 db.admin().listDatabases
包含数据库名称.
Check if db.admin().listDatabases
contains the database name.
If the server has authorization enabled, you will need the appropriate permissions.
这篇关于有没有一种方法可以通过Node.js驱动程序检查Mongo中是否存在数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!