我刚刚开始学习 MongoDB,我正在尝试通过 MongoDB Server 6.0 在本地托管我的 Node.js 应用程序(不使用 Mongoose 或 Atlas)。
我复制了 MongoDB 文档中给出的异步 JavaScript 代码。我确保在执行以下代码之前运行 mongod:
MongoDB服务器启动
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);
它抛出一个错误:
问题是,
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" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&appName=mongosh+1.6.0
C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&appName=mongosh+1.6.0
C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0
C:\>mongosh "mongodb://%COMPUTERNAME%:27017" --quiet --eval "db.getMongo()"
$ mongosh "mongodb://$HOSTNAME:27017" --quiet --eval "db.getMongo()"
mongodb://******:27017/?directConnection=true&appName=mongosh+1.6.0
如果您不将 MongoDB 作为服务运行,那么它会是
mongod --bind_ip_all --ipv6 <other options>
注意,我不喜欢配置
net:
bindIp: <ip_address>
在我看来,这仅在具有多个网络接口的计算机上才有意义。然而,由于 MongoDB 不支持多个接口,它也没有多大意义。 另外,根据您的网络设置,此 IP 可能随时更改。
如果您想仅允许来自本地计算机的连接,请使用
bindIp: localhost
,例如在维护时或用作 Web 服务的后端数据库时。如果您还想允许来自远程计算机的连接,请使用 bindIpAll: true
。
如果您使用的是节点版本 18,请使用此选项(它也适用于 17)
mongoose.connect("mongodb://127.0.0.1:27017/newdb", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.on("error", () => console.log("error connecting to database"));
db.once("open", () => console.log("Connected to database"));
问题是,本地主机别名解析为 IPv6 地址 ::1 而不是 127.0.0.1
来自上面的
@Wernfried Domscheit
答案。我的总结
我只需将
mongodb://localhost/dbName
替换为 mongodb://127.0.0.1:27017/dbName
就可以了。
你可以试试这个:
mongoose.connect("mongodb://0.0.0.0:27017").then(() => {
console.log("database connected)).catch((err) => {
console.log("error while connecting to database")
})