开发者

Getting Mongoose Schema's and Documents without knowing Schema / Collection names?

Short Version: I basically want to do what show collections does in the mongo shell, in mongoose.

Long Version:

I want to create an application that allows users to basically create their own Schema's > Collections > Documents using mongo + mongoose + node.js.

The first step of this application would be to show previously created Collections and their Documents. But since these would be created by a user their names are not known. The co开发者_运维技巧de I've found that came closest was:

function find (collec, query, callback) {
    mongoose.connection.db.collection(collec, function (err, collection) {
    collection.find(query).toArray(callback);
    });
}

But I don't know what the name of the collection is so I can't pass the 'collec' parameter.

So, anyone know how to get the list of collections without knowing their names?


I ended up using node-mongodb-native (the mongo driver that mongoose works on top of) to get the collection names:

var nmn_connect = require('mongoose/node_modules/mongodb').connect;

nmn_connect('mongo://localhost:27017/DATABASE', function(err, db) {
    if(!err){
        db.collectionNames(function(err, names){ // what I was looking for
            if(!err){
                console.log(names);
                db.close();
            }else{
                console.log(err);
                db.close();
            }
        });     
    }else{
        console.log(err)
    }
});

The Object returned by mongoose.connect() has no method similar to collectionNames() that I can find.


I know nothing of mongoose, but this page suggests that you could use mongoose.connection.collections to access all collections: http://mongoosejs.com/docs/api.html

each collection again should have a name attribute.


try this:

mongoose.connection.db.collectionNames(function (err, names) {

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜