Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

db.listCollections() in ExpressJS returns an error

I am using ExpressJs + MongoDB and following code returns an error:

var db = monk(DB_URL);
app.use(function (req, res, next) {
  req.db = db;
  next();
});

app.get("/view_collections", function (req, res) {
    var db = req.db;
    db.listCollections().toArray(function (err, collections) {
        console.log(collections);
    }); 
});

The Error is:

TypeError: db.listCollections is not a function.

Other functions work perfectly. As an example, following code is working:

app.get('/testCollection', function (req, res) {
  var collection = req.db.get('testData');
  collection.find({}, {
    limit: 300,
    sort: {
      timestamp: -1
    }
  }, (e, entries) => {
    res.render('testView', {
      entries: entries
    });
  });
});

I tried both db.getCollectionNames() and db.listCollections() but both return the same error but in the shell db.getCollectionNames() works.

Can someone please tell me how to get a list of MonogoDB collections inside,

app.get("/view_collections", function (req, res) {
    //Here
});
like image 968
kmchmk Avatar asked Oct 12 '17 19:10

kmchmk


2 Answers

I was facing the same error, a fix can be:

MongoClient.connect(url, function(err, client) {


     const db = client.db(DBNAME)

     db.listCollections().toArray(function(err, items) {
        console.log(items)
            //and u can loop over items to fetch the names
            client.close();
    });
})
like image 117
Kushan Avatar answered Oct 05 '22 16:10

Kushan


Maybe this clarifies more:

const url = 'mongodb://localhost:27017/testdb';

MongoClient.connect(url, (err, client) => 

    const db = client.db('testdb');

    db.listCollections().toArray((err, collections) => {

       console.log(collections);

       client.close();
    });

});

Notice, that there is the same 'testdb' in two lines:

const url = 'mongodb://localhost:27017/testdb';

const db = client.db('testdb');

Works the same when 'testdb' in url is missed:

const url = 'mongodb://localhost:27017/';
like image 34
Maupa Avatar answered Oct 05 '22 15:10

Maupa