无法使用Node.js连接到MongoDB。

3

使用Node.js无法连接到MongoDB。

这是我的代码(mdb.js):

var MongoClient = require('mongodb').MongoClient, format = require('util').format;

MongoClient.connect('mongodb://localhost:3000', function(err,db){

    if(err){
         throw err;
    } else {
         console.log("Connected");
    }
    db.close();
});

节点 mdb.js 打印 MongoError:

在此输入图像描述


你是如何启动Mongo的? - undefined
如果您正在使用macOS,可能是因为您正在使用localhost而不是127.0.0.1。 - undefined
8个回答

16

当我将“localhost”更改为127.0.0.1时,它对我有效。


你是否在启用IPv6的系统上,并且mongo只监听127.0.0.1,而不是::1?netstat -an | grep LISTEN(或者你的操作系统相应的命令)将显示更多信息。 - undefined
对我来说也是一样!你知道为什么会这样吗? - undefined

4

将 'localhost' 更改为 127.0.0.1

const {MongoClient} = require('mongodb');
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
const database = 'ecomm';

async function getData()
{
  let result = await client.connect();
  let db = result.db(database);
  let collection = db.collection('products');
  let response = await collection.find({}).toArray();
  console.log(response);
}

getData();

但是,最重要的是,_为什么_? - undefined
这是推理的原因:https://www.mongodb.com/community/forums/t/getting-error-while-connecting-to-mongodb-using-node-js/216431 - undefined

1
你的错误已经解释了自己。Mongo无法找到默认的数据库路径B:/data/db
请创建这个文件夹,或在启动时选择另一个数据库目录。
mongod --dbpath yourPath(C:\myDb)

另外,默认的Mongo端口是27017,因此您需要像这样更改连接字符串"mongodb://@localhost:27017/dbYouWant"
希望这可以帮助您。

谢谢。它开始了,但是有很多很多的消息。测试脚本也正常运行。我没有特定的数据库,所以无法检查它。 - undefined

0

在Windows中,使用0.0.0.0而不是localhost可以解决问题,如下所示:mongodb://0.0.0.0:port/db_name

例如:

mongodb://0.0.0.0:3000/test_db

0
请使用此URL:mongodb://0.0.0.0:3000

0

首先确保你的MongoDB服务器正在运行,方法是在安装MongoDB的目录中运行mongod

然后查看它运行在哪个端口(通常为27017)。然后更新你代码中的URL,就可以了。


0
'mongodb://0.0.0.0:3000' 尝试将其修改为此格式,以便在新版本中正常工作。

0
首先请确认您是否将默认数据库端口从27017更改为3000。 如果没有更改,请尝试下面的代码,它对我有效。
 const { MongoClient } = require("MongoDB");

 // Connection URL
 const url = "mongodb://localhost:27017";
 const client = new MongoClient(URL);

 // Database Name
 const dbName = "myProject";

 async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log("Connected successfully to server");
    const db = client.db(dbName);
    const collection = db.collection("documents");

    // return "done.";
 }

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());

此外,我附上了一张屏幕截图,其中包含输出结果示例输出示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接