谷歌云MongoDB实例连接指南:IP端口查找与Node.js+Mongoose配置
Hey there! I’ve helped many folks transition from mLab to self-hosted MongoDB on Google Cloud, so let’s walk through your questions clearly:
First, a critical pre-requisite: you need to ensure your Google Cloud VM’s firewall allows incoming traffic on MongoDB’s port (default is 27017). Head to the VPC Network > Firewall Rules section in the Cloud Console to create a rule that permits TCP traffic on that port from your app’s IP (use 0.0.0.0/0 only for testing—never for production, as it exposes your database to the entire internet).
Once the firewall is configured, you can connect using the standard MongoDB connection string format:
mongodb://<your_username>:<your_password>@<VM_EXTERNAL_IP>:<PORT>/<target_database>?authSource=admin
- Replace
<VM_EXTERNAL_IP>with your VM’s public IP address - Use
27017as the port if you didn’t customize MongoDB’s setup - The
authSource=adminparameter is essential if you created your database user in the admin database (the standard default setup)
Finding the VM’s IP Address
- Navigate to Google Cloud Console > Compute Engine > VM Instances
- Locate the instance running your MongoDB server
- You’ll see the External IP listed in the instance’s details panel—this is the public IP you’ll use for remote connections
Finding the MongoDB Port
- If you used the default MongoDB installation, the port is
27017 - To confirm or check a custom port:
- SSH into your VM directly from the Cloud Console
- Open the MongoDB config file (typically at
/etc/mongod.conf) with a text editor:sudo nano /etc/mongod.conf - Look for the
netsection, which contains aportfield showing the active listening port - Alternatively, run this command to check which port MongoDB is using:
sudo lsof -i | grep mongod
First, install Mongoose in your project if you haven’t already:
npm install mongoose
Use this code snippet to establish the connection, with built-in error handling for easier debugging:
const mongoose = require('mongoose'); // Replace placeholders with your actual credentials and VM details const mongoURI = 'mongodb://<your_username>:<your_password>@<VM_EXTERNAL_IP>:27017/<your_database_name>?authSource=admin'; async function connectToMongoDB() { try { await mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }); console.log('✅ Successfully connected to MongoDB on Google Cloud!'); } catch (error) { console.error('❌ MongoDB connection failed:', error.message); process.exit(1); // Exit the app if connection fails to avoid hanging } } // Initialize the database connection connectToMongoDB();
Quick additional tips:
- If you enabled SSL on your MongoDB instance, add
ssl: trueto the options object inmongoose.connect() - Double-check that your MongoDB user has the correct read/write permissions for your target database (you can grant roles with the
db.grantRolesToUser()command in the MongoDB shell)
内容的提问来源于stack exchange,提问作者sandeep

