【发布时间】:2013-11-26 12:04:42
【问题描述】:
我正在尝试使用 mongoose 返回一个 dbs 集合列表。我遵循此处列出的指示,但 http://grokbase.com/t/gg/mongoose-orm/122xxxr7qy/mongoose-get-a-list-of-all-collections。所以这是我的代码
var mongoose = require('mongoose');
//if (mongoose.connection.readyState == 0){//checks if already connected to the database
console.log("creating connection to the database");
var Config = require('../configs/config');
var config = new Config();
config = config.getConfig().db.dev;
if (mongoose.connection.readyState = 0 ) {
mongoose.connect("mongodb://austin:password1@paulo.mongohq.com:10023/test1");
console.log('mongoose readyState is ' + mongoose.connection.readyState);
}
var collection;
mongoose.connection.on('open', function (ref) {
console.log('Connected to mongo server.');
});
//trying to get collection names
mongoose.connection.db.collectionNames(function (err, names) {
console.log(names); // [{ name: 'dbname.myCollection' }]
module.exports.Collection = names;
});
唯一的问题是名称返回未定义。那么是否有可能仅使用 vanilla mongoose 返回一个集合列表?
【问题讨论】:
-
不直接熟悉 Mongoose,但我对 Mongo 和节点的一般知识使我相信您的 collectionNames 调用返回未定义,因为您实际上还没有连接。如果它是异步的,则该方法可能会在“打开”返回之前触发。尝试将该块放在 open 函数中。