【发布时间】:2019-10-16 22:54:29
【问题描述】:
本地配置: Node.js 12.2.0
服务器配置: 虚拟主机 Ubuntu 18.04 MongoDB 3.2.22
有连接远程 mongodb 数据库的基本脚本。这将返回错误 - Cannot read property 'db' of null.
有admin 和test 数据库。
对于管理员数据库,我创建了一个用户
db.createUser(
{
user: "root",
pwd: "passw0rd",
roles: [ { role: "root", db: "admin" } ]
}
)
节点 app.js
// app.js
const MongoClient = require("mongodb").MongoClient;
// const url = "mongodb://root:passw0rd@46.173.213.195:27017/admin";
const url = "mongodb://46.173.213.195:27017/test";
const mongoClient = new MongoClient(url, { useNewUrlParser: true });
mongoClient.connect(function(err, client){
const db = client.db("admin");
const collection = db.collection("users");
let user = {name: "Tomy", age: 23};
collection.insertOne(user, function(err, result){
if(err){
return console.log(err);
}
console.log(result.ops);
client.close();
});
});
// package.json
{
"name": "mongoapp",
"version": "1.0.0",
"dependencies": {
"express": "^4.16.0",
"body-parser": "^1.18.0",
"mongodb": "^3.1.0"
}
}
两个网址都返回错误。
我尝试了什么:
- 将 bindIp 更改为 any
///nano etc/mongod.conf
# network interfaces
net:
port: 27017
# bindIp: 127.0.0.1
bindIp: 0.0.0.0
- sudo netstat -ntlp | grep 听
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 17184/mongod
...
...
- 将此代码应用于 iptables
iptables -A INPUT -s 185.228.232.150 -p tcp --destination-port 27017 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -d 185.228.232.150 -p tcp --source-port 27017 -m state --state ESTABLISHED -j ACCEPT
-
sudo systemctl status mongodb表示 db 运行良好
谁能帮忙? 可以在您的计算机上测试代码。
更新: 根据那个帖子https://www.mkyong.com/mongodb/mongodb-bind-failed-errno99-cannot-assign-requested-address-for-socket/bindIp 不应该等于服务器IP。
【问题讨论】:
-
你能通过命令行连接吗?
-
我不打算使用 mongo shell 来处理数据库。还不能使用命令行。
-
我在这里找到了解决方案 - stackoverflow.com/questions/49716190/… 剩下的问题是为什么 mongo 拒绝开始使用这个 IP
标签: node.js mongodb ubuntu-18.04