代码之家  ›  专栏  ›  技术社区  ›  rap-2-h

将数据库与mongodb`connect一起使用`

  •  0
  • rap-2-h  · 技术社区  · 6 年前

    我可以通过以下方式连接MongoDB:

    const client = await MongoClient.connect('mongodb://user:pass@host/mydb', {
        useNewUrlParser: true
    })
    

    然后为了执行查询,我必须使用 db 对象。我可以通过以下途径得到:

    const db = await client.db('mydb')
    

    这似乎是多余的,因为我必须给数据库命名两次。我能避开第二步吗?(假设我无法更改给定给connect函数的URL)

    2 回复  |  直到 6 年前
        1
  •  2
  •   Yury Fedorov    6 年前

    你可以用 db() 没有任何争论。在这种情况下,将使用连接字符串中的名称。

    数据库名称 一串 可选择的 要使用的数据库的名称。如果未提供,请使用连接字符串中的数据库名称。

    const db = await client.db() // mydb is used
    
        2
  •  0
  •   chridam Gino Claudi    6 年前

    您不能更改给定给connect函数的url,但是您可以通过解析url并获取名称(即)来提取db名称。

    const url = require('url')
    const { MongoClient } = require('mongodb')
    
    const mongodbServerUrl = 'mongodb://user:pass@host/mydb'
    const mongoPathName = url.parse(mongodbServerUrl).pathname
    const dbName = mongoPathName.substring(mongoPathName.lastIndexOf('/') + 1)
    
    const client = await MongoClient.connect(mongodbServerUrl, {
        useNewUrlParser: true
    })
    
    const db = await client.db(dbName)