【问题标题】:Trying to get a list of collections from mongoose试图从 mongoose 获取收藏列表
【发布时间】: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 函数中。

标签: node.js mongodb mongoose


【解决方案1】:

刚刚遇到了这个答案,虽然它可能在看起来 collectionNames 已从可用函数名称中删除以支持 listCollections 的时候起作用

另一个堆栈溢出帖子有一个工作示例:https://stackoverflow.com/a/29461274/4127352

这里是原始文档的链接:http://mongodb.github.io/node-mongodb-native/2.0/meta/changes-from-1.0/

【讨论】:

  • 如果有帮助:我在使用 bluebird 的 Promise.promisifyAll(mongoose.connection.db) + 包 asyncawait 后尝试使用 listCollectionsAsync(),但没有成功(无缘无故地调用 listCollectionsAsync() 时挂起)。然而,在 console.log(mongoose.connection.db) 检查可用方法之后,我发现了一个未记录的 collections() 函数(承诺为 collectionsAsync()),它完美地工作 O_o(猫鼬 4.3.7)
  • 危险的例子,我快速复制代码并没有注意到它会丢弃数据库中的集合。所以请编辑以包含列出集合的实际代码非常小心!
【解决方案2】:

尝试在连接后运行您的集合名称功能。

mongoose.connection.on('open', function (ref) {
    console.log('Connected to mongo server.');
    //trying to get collection names
    mongoose.connection.db.listCollections().toArray(function (err, names) {
        console.log(names); // [{ name: 'dbname.myCollection' }]
        module.exports.Collection = names;
    });
})

【讨论】:

  • 正是我需要的谢谢
  • -1 因为它不再起作用,请更新答案,然后我将删除反对票。对于其他人,请参阅 Squivo 的回答。
  • - 1 因为,截至今天,这不是有效的答案。使用mongoose.connection.db.listCollections().toArray((error, collections) => { //... })
  • (自@zbr 和@Vikram 的cmets 以来,此答案已得到纠正)
【解决方案3】:

这是我设法获取连接数据库上所有名称的方法。

var mongoose = require('mongoose');
var collections = mongoose.connections[0].collections;
var names = [];

Object.keys(collections).forEach(function(k) {
    names.push(k);
});

console.log(names);

此解决方案在 mongoose 4.4.19 上运行良好。

【讨论】:

  • 这不会列出连接数据库中的集合!它列出了使用mongoose.model 函数注册的集合。它甚至在一个空数据库上列出集合,实际上甚至在连接到一个数据库之前。
【解决方案4】:

如果您只使用 Mongoose 模型,这就是您所需要的:

const connection = mongoose.connection;
Object.keys(connection.models).forEach((collection) => {
  // You can get the string name.
  console.info(collection);
  // Or you can do something else with the model.
  connection.models[collection].remove({});
});

【讨论】:

    【解决方案5】:

    与上面的最佳答案类似,但此代码显示每个集合的名称,没有其他附加信息(如类型、选项、信息等)。

    const namesList = [];
    mongoose.connection.on("open", function (ref) {
      console.log("Connected to mongo server.");
      //trying to get collection names
      mongoose.connection.db.listCollections().toArray(function (err, names) {
        for (let i = 0; i < names.length; i++) {
          // gets only the name and adds it to a list
          const nameOnly = names[i].name;
          namesList.push(nameOnly);
        }
        console.log(namesList);
        module.exports.Collection = namesList;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-13
      • 2017-02-11
      • 1970-01-01
      • 2016-05-04
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多