问题
My MongoDB server is hosted on google-cloud VM. I wish to create App Engine microservice. to test connectivity,
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")}
});
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)]: {} }
i get exactly the same error when deployed the service [gcloud app deploy]
please help.
回答1:
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.
The issue is with how you were connecting. You have to create the URI like this:
let uri = `mongodb://${user}:${pass}@${host}:${port}`;
Where as, in your code, you have this:
const url = 'mongodb://testmongodb:27017';
You are missing the user and password in your URI (assuming that testmongodb is your hostname).
回答2:
When connecting to a server on the same machine, use mongodb://localhost:27017.
回答3:
Thank you all for your support and answers.
seems the change I needed to do in my app.yaml file.env: standard does not support mongodb. you will have to use
env: flex in your yaml file which will be used by gcloud app deploy app.yaml command
来源:https://stackoverflow.com/questions/51515839/nodejs-not-able-to-connect-to-mongodb-on-cloud-shell