首页 > 解决方案 > db.getCollectionInfos 不是函数

问题描述

我正在编写一个 MERN 应用程序,并尝试使用该db.getCollectionInfos 方法获取我的 MongoDB 数据库中的所有集合名称。但是,我收到以下错误:

Error: db.getCollectionInfos is not a function

这是我的代码。数据库已连接,因为它已连接并返回文档数据以及我在我的应用程序中拥有的其他路线。

有人可以帮我弄清楚我做错了什么吗?

  mongoose.connect(process.env.DATABASE, { useNewUrlParser: true });
  const db = mongoose.connection;

  app.post("/fetchdatabasecollections", (req, res) => {
    let regex = /someRegEx/g;
    let collections = db.getCollectionInfos({ name: { $regex: regex } });
  })

标签: node.jsmongodbexpressmongoose

解决方案


getCollectionInfos是 mongo shell 方法,不是由 nodejs 驱动程序提供的。listCollections改为使用

const filter = { name: { $regex: regex } };
const collectionInfos = await mongoose.connection.db.listCollections(filter).toArray();

推荐阅读