Node.js无法连接到Cloud Shell上的mongodb [英] Nodejs not able to connect to mongodb on cloud shell

查看:205
本文介绍了Node.js无法连接到Cloud Shell上的mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的MongoDB服务器托管在google-cloud VM上.我希望创建App Engine微服务.测试连通性,

My MongoDB server is hosted on google-cloud VM. I wish to create App Engine microservice. to test connectivity,

我的server.js看起来像

my server.js looks like

const MongoClient = require('mongodb').MongoClient;
const test = require('assert');
// Connection url
const url = 'mongodb://testmongodb:27017';
// Database Name
const dbName = 'test';
// Connect using MongoClient
MongoClient.connect(url, { useNewUrlParser: true },function(err, client) {
if(err){console.log(err)}
else {console.log("Connected successfully")}
});

如果我通过另一个虚拟机连接,它可以完美地工作.但是在尝试通过 Google Cloud Shell 执行(npm start)相同的代码时不起作用.我收到错误

it works perfectly if i connect via another vm. But does not work when trying to execute (npm start) the same code via Google Cloud Shell. I get the error

{ MongoNetworkError: failed to connect to server [testmongodb:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND testmongodb testmongodb:27017]
    at Pool.<anonymous> (/home/google/mng/node_modules/mongodb-core/lib/topologies/server.js:562:11)
    at emitOne (events.js:116:13)
    at Pool.emit (events.js:211:7)
    at Connection.<anonymous> (/home/google/mng/node_modules/mongodb-core/lib/connection/pool.js:316:12)
    at Object.onceWrapper (events.js:317:30)
    at emitTwo (events.js:126:13)
    at Connection.emit (events.js:214:7)
    at Socket.<anonymous> (/home/google/mng/node_modules/mongodb-core/lib/connection/connection.js:245:50)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:116:13)
  name: 'MongoNetworkError',
  message: 'failed to connect to server [testmongodb:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND testmongodb testmongodb:27017]',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }

部署服务[gcloud app deploy]时,我得到完全相同的错误

i get exactly the same error when deployed the service [gcloud app deploy]

请帮助.

推荐答案

App Engine Standard不支持使用与您使用的相同的库连接到MongoDB实例. 此示例同样适用于标准版和灵活版.

App Engine Standard does support connecting to a MongoDB instance with the very same library that you were using. This example works for Standard and Flexible as well.

问题在于您的连接方式.您必须像这样创建URI:

The issue is with how you were connecting. You have to create the URI like this:

let uri = `mongodb://${user}:${pass}@${host}:${port}`;

在代码中的位置如下:

const url = 'mongodb://testmongodb:27017';

您在URI中缺少用户名和密码(假设testmongodb是您的主机名).

You are missing the user and password in your URI (assuming that testmongodb is your hostname).

这篇关于Node.js无法连接到Cloud Shell上的mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆