我使用在新vpc(Amazon Linux)上部署的ssh隧道设置了mongo数据库,我按照此处的说明进行操作:
https://docs.aws.amazon.com/quickstart/latest/mongodb/step2.html
我能够通过PuTTY,Mongo Compass和Robo3T连接到我的数据库,但是我找不到通过Node JS连接到我的数据库的方法。我尝试使用“ tunnel-ssh”包,但仍无法连接到数据库。我收到此错误:
AssertionError [ERR_ASSERTION]: null == { MongoNetworkError: failed to connect to server [PrimaryReplicaNode0-PrivateIPs:27017] on first connect [MongoNetworkError: connect ETIMEDOUT 10...
这是我的代码:
import { MongoClient, ObjectID } from 'mongodb';
import { format } from 'util';
import tunnel from 'tunnel-ssh';
import assert from 'assert';
const user = encodeURIComponent('username');
const password = encodeURIComponent('password');
const authMechanism = 'SCRAM-SHA-1';
const url = format('mongodb://%s:%s@PrimaryReplicaNode0-PrivateIPs:27017/?authMechanism=%s&authSource=admin&ssl=false', user, password, authMechanism);
const sshConfig = {
usesrname: 'ec2-user',
host: 'LinuxBastion-PublicDNS(IPv4)',
port: 22,
dstHost: 'PrimaryReplicaNode0-PrivateIPs',
dstPort: 27017,
privateKey:require('fs').readFileSync('ssh/key-pair.pem'),
localHost:'127.0.0.1',
localPort: 3000
};
var tnl = tunnel (sshConfig, (error, server) => {
if (error){
console.log("SSH connection error: " + error);
}
MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
assert.equal(null, err);
console.log("Connected correctly to server!");
tnl.close();
}
}
我在Google上搜索了整整一周,但是一切仍然是负面的,因此任何人都对此有经验,请帮帮我一下。
谢谢。