仅在数据库存在的情况下创建MongoDB集合

问题描述 投票:0回答:1

我正在尝试使用Node.js MongoDB驱动程序从节点api创建集合,要求是仅在给定端口上运行的mongod实例中已经存在给定数据库时,才创建集合。

app.js

MongoClient.connect(url, { useUnifiedTopology: true }, function(error, db) {
      if (error != null)
      {
        console.log(error);
        return res.status(500).json({ error: error.message });
      }

      var dbo = db.db(dbname);
      dbo.createCollection(collname, function(error, res) {
        if (error != null){
          console.log(error);
          return res.status(500).json({ error: error.message });
        }
        console.log("Collection created!");
        db.close();
      });
      res.json({result:"Collection created!"});
});

任何帮助将不胜感激。

node.js mongodb mongodb-query node-mongodb-native
1个回答
0
投票
首先,您必须通过以下代码获取数据库列表:

db.adminCommand( { listDatabases: 1, nameOnly: true} )

© www.soinside.com 2019 - 2024. All rights reserved.