【问题标题】:MongoRuntimeError Unable to parse with URLMongoRuntimeError 无法解析 URL
【发布时间】:2022-12-11 17:16:45
【问题描述】:

我正在尝试使用 node js mongodb 驱动程序连接到 mongodb,我正在一个 cypress 项目中执行此操作。我得到标题中的错误。下面是我的代码的简化版本。

import {MongoClient} from 'mongodb';

export class SomeRepository {

    static insertSomething(): void {
        // Error in the line below: MongoRuntimeError Unable to parse localhost:27017 with URL
        const client = new MongoClient('mongodb://localhost:27017');
    }
}

Mongodb 正在运行,因为我可以从终端连接。还尝试用 127.0.0.1 替换 localhost 并将 authSource 参数添加到连接字符串。

我提到 cypress 的原因是因为在一个只连接到 mongodb 的简单节点项目中,一切都按预期工作。下面的 Package.json

{
  "name": "e2e",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "cypress": "10.8.0",
    "cypress-wait-until": "1.7.2",
    "headers-utils": "3.0.2",
    "mongodb": "4.10.0",
    "otplib": "12.0.1",
    "pg": "8.7.3",
    "pg-native": "3.0.1",
    "typescript": "4.9.3"
  }
}

【问题讨论】:

  • 当你说这是在赛普拉斯项目中时,你是否试图在赛普拉斯测试中执行这段代码?
  • 是的,这就是我要说的。我基本上有这个: cy.then(() => { SomeRepository.insertSomething(); });

标签: mongodb cypress mongodb-nodejs-driver


【解决方案1】:

错误在于您传递 url 的方式,您必须遵循一种模式,在 mongodb 中连接您需要具有我将在下面传递的这种模式:

格式:

mongodb://<user>:<password>@<host>

具有填充值的格式:

mongodb://root:mypassword@localhost:27017/

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多