【问题标题】:How can I find the Collection exist in MongoDB 4.2 ? using Node.JS如何找到 MongoDB 4.2 中存在的集合?使用 Node.JS
【发布时间】:2019-11-22 05:41:13
【问题描述】:

我想在 mongoDB 4.2 中创建集合,但我想检查它是否存在?我正在使用 Node.JS 和 Express,但我没有使用 Mongoose。

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    请试试这个 ::

    const MongoClient = require('mongodb').MongoClient;
    
    // Connection URL
    const url = 'your DB url';
    
    // Database Name
    const dbName = 'your DB name';
    
    // Create a new MongoClient
    const client = new MongoClient(url);
    
    // Use connect method to connect to the Server
    client.connect(async function (err) {
        if (err) console.log('Err::', err)
        console.log("Connected successfully to server");
        const collection = await client.db(dbName).listCollections({}, { nameOnly: true }).toArray()
        console.log('List of all collections :: ', JSON.stringify(collection))
    
        client.close();
    });
    

    【讨论】:

    • 另外,db.getCollectionNames() 应该可以在 shell/任何客户端(如 robo3T)中工作..
    • 我得到这个错误:连接到服务器成功(节点:23868)UnhandledPromiseRejectionWarning:MongoError:调用MongoClient.prototype.db之前必须连接MongoClient
    • @samurai_code : 你能用你尝试过的代码来编辑你的问题吗!!
    • @samurai_code : 连接后代码应该可以工作,错误可能被抑制了左右,所以这个错误是由于连接不正确,请检查:stackoverflow.com/questions/55768876/…
    • @samurai_code :或者一般情况下,如果您不想在创建集合之前执行数据库操作以获取集合列表,那么您可以继续执行 createCollection() 它应该会出错如果集合已经存在于同一个数据库中,则退出。
    【解决方案2】:

    您可以使用listCollections 查找数据库中的所有集合,然后遍历returned array 以获取名称。

    db.listCollections().toArray(function(err, items) {
        console.log(items)
            //and u can loop over items to fetch the names
      });
    

    【讨论】:

    • 感谢您的回答,错误:db.listCollections(...).toArray 不是函数
    猜你喜欢
    • 2017-03-28
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多