我在 AWS EC2 Linux 机器上运行 MongoDB 服务器 v6.0.4,这是可公开访问的。
使用 MongoDB:6.0.4 使用 Mongosh:1.8.0
/etc/mongod.conf
# network interfaces
net:
port: 27017
bindIp: ::,0.0.0.0 # Enter 0.0.0.0,:: to bind to all IPv4 and IPv6 addresses or, alternatively, use the net.bindIpAll setting.
security:
authorization: enabled
keyFile: /etc/mongodkeyfile.key
#operationProfiling:
replication:
replSetName: rs0
能够在同一台机器上通过mongosh连接进行所有的DB操作,
当我从我的 Mac 机器上 ping 时,EC2 机器正在响应。
而当我尝试通过 Nodejs 应用程序连接时,出现以下错误
MongoServerSelectionError: getaddrinfo ENOTFOUND ip-xx-x-xx-xxx.ap-south-1.compute.internal
at Timeout._onTimeout (/Users/durgalovababupadala/myprojects/continuum-electrolite/ev-server/node_modules/mongodb/lib/sdam/topology.js:293:38)
at listOnTimeout (node:internal/timers:569:17)
at process.processTimers (node:internal/timers:512:7)
这是我的示例代码,
const { MongoClient } = require("mongodb");
// Replace the uri string with your connection string.
const uri = "mongodb://<user>:<pwd>@<EC2-PublicIP>:27017/<dbname>?replicaSet=rs0&useUnifiedTopology=true";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db('test');
console.log(database);
const myColl = database.collection("pizzas");
const doc = { name: "Neapolitan pizza", shape: "round" };
const result = await myColl.insertOne(doc);
console.log(
`A document was inserted with the _id: ${result.insertedId}`,
);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
提前致谢,