Trying to get a list of collections from mongoose

后端 未结 4 1564
迷失自我
迷失自我 2020-12-16 13:55

I\'m trying to return a list of a dbs collections using mongoose. I\'m following the directions set out here but http://grokbase.com/t/gg/mongoose-orm/122xxxr7qy/mongoose-ge

相关标签:
4条回答
  • 2020-12-16 14:25

    Try running your collection names function after connection.

    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;
        });
    })
    
    0 讨论(0)
  • 2020-12-16 14:28

    Just came across this answer and though it may have worked at the time it appears collectionNames has been removed from the available function names in favour of listCollections

    This other stack overflow post has a working example: https://stackoverflow.com/a/29461274/4127352

    Here is the link to the original docs: http://mongodb.github.io/node-mongodb-native/2.0/meta/changes-from-1.0/

    0 讨论(0)
  • 2020-12-16 14:36

    If you are only working with Mongoose Models, that is all you need:

    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({});
    });
    
    0 讨论(0)
  • 2020-12-16 14:47

    Here is how I managed to obtain all the names on the connected db.

    var mongoose = require('mongoose');
    var collections = mongoose.connections[0].collections;
    var names = [];
    
    Object.keys(collections).forEach(function(k) {
        names.push(k);
    });
    
    console.log(names);
    

    This solution works good on mongoose 4.4.19.

    0 讨论(0)
提交回复
热议问题