I am trying to connect my mongodb server with node js app but its not working idk why even server mongod is running

huangapple go评论55阅读模式
英文:

I am trying to connect my mongodb server with node js app but its not working idk why even server mongod is running

问题

const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
const url = "mongodb://localhost:27017";
const dbName = "fruitsDB";
const client = new MongoClient(url, { useNewUrlParser: true });
client.connect(function (err) {
    assert.equal(null, err);
    console.log("connected to the server");
    const db = client.db(dbName);
    client.close();
});

<details>
<summary>英文:</summary>

const MongoClient = require("mongodb").MongoClient;
const assert = require("assert");
const url = "mongodb://localhost:27017";
const dbName = "fruitsDB";
const client = new MongoClient(url, { useNewUrlParser: true });
client.connect(function (err) {
assert.equal(null, err);
console.log("connected to the server");
const db = client.db(dbName);
client.close();
});

   [![image description][1]][1]

   [1]: https://i.stack.imgur.com/crZXW.png

This code should show in the terminal &quot;connected to the server.&quot;

</details>


# 答案1
**得分**: 0

你应该使用 `localhost` IP 地址来连接 MongoDB。
我不知道为什么,但当我尝试使用这个 URL 时它不起作用:```"mongodb://localhost:27017"```

请使用这个:

```use const url = "mongodb://127.0.0.1:27017";```

<details>
<summary>英文:</summary>

You should use `localhost` ip address for connecting to mongodb.
I don&#39;t know why but it was not working when i try to do with this url ```&quot;mongodb://localhost:27017&quot;```

Go with this one

```use const url = &quot;mongodb://127.0.0.1:27017&quot;;```

</details>



huangapple
  • 本文由 发表于 2023年6月29日 12:30:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定