Node.js 使用带有mongodb`connect的数据库`

Node.js 使用带有mongodb`connect的数据库`,node.js,mongodb,Node.js,Mongodb,我可以通过以下方式连接到mongodb: const client = await MongoClient.connect('mongodb://user:pass@host/mydb', { useNewUrlParser: true }) 然后为了执行查询,我必须使用db对象。我可以通过以下途径获得: const db = await client.db('mydb') 这似乎是多余的,因为我必须给数据库命名两次。我可以避免第二步吗?(假设我无法更改给定给connect函数的UR

我可以通过以下方式连接到mongodb:

const client = await MongoClient.connect('mongodb://user:pass@host/mydb', {
    useNewUrlParser: true
})
然后为了执行查询,我必须使用
db
对象。我可以通过以下途径获得:

const db = await client.db('mydb')
这似乎是多余的,因为我必须给数据库命名两次。我可以避免第二步吗?(假设我无法更改给定给connect函数的URL)

您可以使用,无需任何参数。在这种情况下,将使用连接字符串中的名称

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

您可以不带任何参数地使用。在这种情况下,将使用连接字符串中的名称

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


您不能更改给定给connect函数的URL,但您可以通过解析URL并获取名称(即

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)

您不能更改给定给connect函数的URL,但您可以通过解析URL并获取名称(即

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)