【问题标题】:Can't connect to MongoDB 6.0 Server locally using Nodejs driver无法使用 Nodejs 驱动程序在本地连接到 MongoDB 6.0 服务器
【发布时间】:2022-11-29 16:51:10
【问题描述】:

我刚刚开始学习 MongoDB,我正在尝试通过 MongoDB Server 6.0 在本地托管我的节点 js 应用程序(不使用猫鼬或地图集)

我复制了 MongoDB 文档中给出的异步 javascript 代码。我确定要跑蒙神在执行下面的代码之前 MongoDB server started

const { MongoClient } = require("mongodb");

// Connection URI
const uri =
  "**mongodb://localhost:27017**";

// Create a new MongoClient
const client = new MongoClient(uri);

async function run() {
  try {
    // Connect the client to the server (optional starting in v4.7)
    await client.connect();

    // Establish and verify connection
    await client.db("admin").command({ ping: 1 });
    console.log("Connected successfully to server");
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}
run().catch(console.dir);

它抛出一个错误:image of the error it's throwing

【问题讨论】:

  • 如果你使用const uri = "mongodb://127.0.0.1:27017";会发生什么?
  • 你是从窗户跑的吗??你能从windows的服务启动mongodb然后重试吗
  • 有效!我都做了。首先,从服务中重新启动 mongodb 并将 localhost 更改为 127.0.0.1 并成功连接。太感谢了!

标签: node.js mongodb async-await localhost mongodb-nodejs-driver


【解决方案1】:

问题是,localhost 别名解析为 IPv6 地址 ::1 而不是 127.0.0.1

但是,net.ipv6 默认为 false。

最好的选择是使用以下配置启动 MongoDB:

net:
  ipv6: true
  bindIpAll: true

或者

net:
  ipv6: true
  bindIp: localhost

然后所有变体都应该起作用:

C:>mongosh "mongodb://localhost:27017?authSource=admin" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?authSource=admin&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0

C:>mongosh "mongodb://127.0.0.1:27017?authSource=admin" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?authSource=admin&directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0

C:>mongosh "mongodb://[::1]:27017?authSource=admin" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?authSource=admin&directConnection=true&appName=mongosh+1.6.0

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多