无法使用Nodejs驱动程序在本地连接到MongoDB 6.0服务器

uubf1zoe  于 2022-12-03  发布在  Go
关注(0)|答案(1)|浏览(172)

我刚刚开始学习MongoDB,我正在尝试通过MongoDB Server 6.0在本地托管我的node js应用程序(不使用mongoose或atlas)
我复制了MongoDB文档中给出的异步javascript代码。我确保在执行下面的代码MongoDB server started之前运行mongod

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

vc9ivgsu

vc9ivgsu1#

问题是,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

相关问题