ExpressJS中的db.listCollections()返回错误

问题描述 投票:2回答:2

我正在使用ExpressJs + MongoDB,以下代码返回错误:

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);
    }); 
});

错误是:

TypeError: db.listCollections is not a function.

其他功能完美。例如,以下代码正在运行:

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
    });
  });
});

我尝试了db.getCollectionNames()db.listCollections(),但两者都返回相同的错误但在shell db.getCollectionNames()工作。

有人可以告诉我如何获取里面的MongoDB集合列表,

app.get("/view_collections", function (req, res) {
    //Here
});
node.js mongodb express
2个回答
3
投票

我遇到了同样的错误,修复可以是:

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();
    });
})

1
投票

也许这澄清了更多:

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();
    });

});

请注意,两行中有相同的'testdb':

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

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

当错过url中的'testdb'时,工作方式相同:

const url = 'mongodb://localhost:27017/';
© www.soinside.com 2019 - 2024. All rights reserved.