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

kmc*_*hmk 4 mongodb node.js express

我正在使用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);
    }); 
});
Run Code Online (Sandbox Code Playgroud)

错误是:

TypeError: db.listCollections is not a function.
Run Code Online (Sandbox Code Playgroud)

其他功能完美运行。例如,下面的代码正在工作:

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
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

我尝试了两者db.getCollectionNames()db.listCollections()但都返回了相同的错误,但是在外壳程序中db.getCollectionNames()有效。

有人可以告诉我如何获取内部的MonogoDB集合列表,

app.get("/view_collections", function (req, res) {
    //Here
});
Run Code Online (Sandbox Code Playgroud)

小智 5

我遇到了同样的错误,可以通过以下方法解决:

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();
    });
})
Run Code Online (Sandbox Code Playgroud)