使用Mongoose获取所有数据库的列表 [英] Getting list of all databases with Mongoose

查看:542
本文介绍了使用Mongoose获取所有数据库的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有一些类似的问题,但所有问题都涉及使用 MongoDB NodeJS驱动程序代替猫鼬ODM .

There are some similar questions but all of them involves using the MongoDB NodeJS driver instead of Mongoose ODM.

我阅读了文档,但找不到此类功能.

I read the docs but couldn't find such functionality.

推荐答案

您不能直接从mongoose提供的连接中获取列表,但是使用mongo Admin对象很容易,因为它包含一个名为listDatabases:

You can't directly get the list from the connection provided by mongoose, but it's easy to do with the mongo Admin object as it contains a function called listDatabases:

var mongoose = require('mongoose')
    , Admin = mongoose.mongo.Admin;

/// create a connection to the DB    
var connection = mongoose.createConnection(
    'mongodb://user:pass@localhost:port/database');
connection.on('open', function() {
    // connection established
    new Admin(connection.db).listDatabases(function(err, result) {
        console.log('listDatabases succeeded');
        // database list stored in result.databases
        var allDatabases = result.databases;    
    });
});

这篇关于使用Mongoose获取所有数据库的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆