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
});
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();
});
})
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/';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With