October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Connect Node.js to a MongoDB Database on a VPS

Connect a Node.js app to MongoDB on a VPS using a secure URI, reusable MongoClient, private networking, least-privilege authentication, validated TLS and a systematic timeout troubleshooting checklist.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the official mongodb Node.js driver with a MongoDB URI that identifies your VPS, port, database, credentials and security options. Make MongoDB reachable only on a private or tightly firewalled interface, authenticate with a least-privilege user, verify the session with a ping, reuse one client for the life of the process, and close it during graceful shutdown.

What the connection actually requires

A Node.js process does not connect to a VPS in the abstract. It opens a TCP connection to the address and port where MongoDB is listening, negotiates authentication (and, when enabled, TLS), then selects a database through the MongoDB wire protocol. Every layer must agree:

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Driver: the official mongodb package installed in your application.
  • URI: a MongoDB connection string containing the host, port, database and authentication settings.
  • Listener: MongoDB’s net.bindIp must include an address reachable from the Node.js host.
  • Firewall: the VPS firewall and any cloud security group must allow the application host to reach the MongoDB port.
  • Identity: the username, password, authentication database and mechanism must match a user configured on the server.
  • Trust: a TLS-enabled deployment needs a certificate that the client can validate.

A timeout usually means the network path or listener is wrong. An authentication error normally means the credentials, authSource or mechanism is wrong. A TLS error points to certificate trust, hostname validation, expiry or file permissions.

Install the official Node.js driver

Install it in the application directory

npm install mongodb

The package is the driver; it is not a MongoDB server and does not create users or alter the VPS firewall. Install it on the machine that runs your Node.js application, then keep the package version controlled in package.json and your lockfile.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Use an environment variable for the URI

Do not put a production password directly in source code or commit it to a repository. Set a secret in the process environment or a deployment secret manager:

MONGODB_URI=mongodb://app_user:[email protected]:27017/game_api?authSource=admin
MONGODB_DB=game_api

When a username or password contains characters that have meaning in a URI, such as @, :, /, ? or #, percent-encode that credential before placing it in the URI. Keep the database name separate in MONGODB_DB if you want to change the application database without rebuilding the connection string.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build the MongoDB URI for a VPS

A conventional self-managed URI has this shape:

mongodb://USER:PASSWORD@DB_HOST:27017/APP_DB?authSource=admin
Part Purpose What to use on a VPS
mongodb:// Protocol for a standard MongoDB connection Use this for a self-managed MongoDB listener
USER MongoDB account used by the application A dedicated account with only the permissions the application needs
PASSWORD Password for that account Store it in a secret, and URI-encode reserved characters
DB_HOST Hostname or address of the VPS running MongoDB A private DNS name or private address where possible
27017 Default MongoDB TCP port Use the actual configured port if the server uses a different one
APP_DB Initial database selected by the application The database where the app’s collections live
authSource=admin Database in which MongoDB looks up the user’s credentials Use the authentication database configured when the user was created; it is not always admin

The path database and the authentication database are separate concepts. For example, an account created in admin can be authorized to work in game_api; that requires /game_api?authSource=admin. If the account was created in game_api, set authSource=game_api instead. Select the authentication mechanism configured on the server; do not assume that changing the database name changes where credentials are checked.

Configure MongoDB networking safely

When Node.js and MongoDB share one VPS

The safest arrangement is to keep MongoDB on loopback or a private socket path and have Node.js connect locally. A loopback listener prevents an external host from reaching the database directly. You still need MongoDB authentication, because local reachability is not an authorization boundary.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

When the application and database are on separate VPS instances

Prefer the provider’s private network or a VPN. Configure MongoDB’s net.bindIp to include only the private interface (or another tightly controlled address), not every public interface. Then permit the MongoDB port in the database VPS firewall only from the application host or private network. Avoid opening port 27017 to the entire internet.

The effective path is: Node.js host address, private route or VPN, database host address, MongoDB listener, then firewall policy. A correct URI cannot overcome a listener that is bound only to 127.0.0.1 or a firewall that drops the packet.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create an application account with least privilege

Enable MongoDB authentication and create a separate account for the application rather than using an administrator account. Grant only the actions and databases the application requires. Keep administrative credentials out of the application environment.

  • Use a unique username and a long, randomly generated password.
  • Record the database in which the user was created; that value determines authSource.
  • Grant read/write access only to the application database unless a broader role is genuinely required.
  • Rotate the credential through the deployment process, updating the secret and restarting the application in a controlled window.
  • Never commit the URI, a password file or a TLS private key to source control.

Authentication proves who the client is; authorization determines what that identity may do. Both must be configured before a remote listener is exposed.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Connect once and reuse the client

Create one MongoClient for the Node.js process and reuse it for requests. Opening a new client for every HTTP request wastes handshakes and sockets and can exhaust the server’s connection limits. The driver manages a pool behind that client.

import { MongoClient } from "mongodb";

const uri = process.env.MONGODB_URI;
if (!uri) {
  throw new Error("MONGODB_URI is not set");
}

const client = new MongoClient(uri, {
  connectTimeoutMS: 10_000,
  serverSelectionTimeoutMS: 10_000,
});

await client.connect();
await client.db("admin").command({ ping: 1 });

const db = client.db(process.env.MONGODB_DB || "app");
const items = db.collection("items");

export { client, db, items };

process.on("SIGTERM", async () => {
  await client.close();
  process.exit(0);
});

The explicit connect() makes startup fail early, while the ping command verifies that the authenticated session can actually reach MongoDB. You can also let the driver connect lazily on the first operation, but an explicit startup check gives your process manager a clear failure instead of allowing the first user request to discover a bad configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the shared database handle in request code

import express from "express";
import { db } from "./mongo.js";

const app = express();

app.get("/items", async (req, res, next) => {
  try {
    const rows = await db.collection("items")
      .find({ ownerId: req.user.id })
      .limit(100)
      .toArray();
    res.json(rows);
  } catch (error) {
    next(error);
  }
});

app.listen(process.env.PORT || 3000);

Do not call client.close() at the end of each route. Close it only when the process is shutting down. Handle both SIGTERM (used by many service managers and containers) and, if your deployment needs it, SIGINT for local termination.

Set connection time limits deliberately

connectTimeoutMS limits how long the driver waits while establishing a network connection. serverSelectionTimeoutMS limits how long it searches for a suitable MongoDB server. The example uses 10,000 milliseconds for each, so a broken route produces a bounded error instead of hanging indefinitely.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

These settings do not make an unreachable server reachable. They make failure observable and allow a process manager to restart or mark the service unhealthy. Log the resulting driver error, but do not log the complete URI or password.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Enable TLS without disabling validation

URI or options

For encrypted transport, add tls=true to the URI or pass tls: true to MongoClient. If the server certificate is signed by a private certificate authority that the operating system does not trust, provide that CA file:

const client = new MongoClient(process.env.MONGODB_URI, {
  tls: true,
  tlsCAFile: "/etc/ssl/mongodb/ca.pem",
  connectTimeoutMS: 10_000,
  serverSelectionTimeoutMS: 10_000,
});

The certificate must be valid for the hostname in the URI, within its validity period and readable by the Node.js process. Set file ownership and permissions so the application can read the CA file without making private key material broadly accessible.

Do not use insecure bypass flags in production

tlsAllowInvalidCertificates, tlsAllowInvalidHostnames and tlsInsecure can be useful for a short diagnostic in a controlled test environment, but they disable certificate or hostname validation. Leaving one enabled allows an attacker to impersonate the server or intercept traffic. Fix the CA chain, hostname, expiry or file permissions instead.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use X.509 when certificate authentication is required

X.509 authentication uses TLS certificates rather than a password. Configure the deployment with authMechanism=MONGODB-X509, keep tls=true, and supply the client certificate and private key in the form expected by your driver and server configuration. If a certificate path is placed in a URI, URI-encode that path. The client certificate must chain to a CA trusted by MongoDB, and its subject must map to an authorized MongoDB user.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A typical options shape is:

const client = new MongoClient(process.env.MONGODB_URI, {
  tls: true,
  tlsCertificateKeyFile: "/etc/ssl/mongodb/client.pem",
  tlsCAFile: "/etc/ssl/mongodb/ca.pem",
  authMechanism: "MONGODB-X509",
});

Protect the certificate-key file like a password. X.509 is an available mechanism only when the server, certificates and user mapping have been configured for it; adding the option to an ordinary password-authenticated deployment will not make authentication work.

Verify each layer before debugging application code

  1. Resolve the database name: from the application VPS, confirm that DB_HOST resolves to the intended private or public address.
  2. Test the route and port: verify that traffic from the application host can reach the configured MongoDB port. A timeout at this stage is not a password problem.
  3. Inspect net.bindIp: ensure MongoDB listens on the interface used by the URI. A process bound only to loopback cannot accept a connection from another VPS.
  4. Inspect firewall and security-group rules: allow the application host or private network, and remove broad internet exposure.
  5. Confirm the service and port: check that MongoDB is running and that the URI port matches its configured listener.
  6. Check identity settings: verify username, password, authSource and authentication mechanism against the account’s server configuration.
  7. Check TLS details: verify the CA chain, certificate hostname, expiry and client-key permissions. Do not turn on invalid-certificate or invalid-hostname options as a production workaround.
  8. Run the driver ping: once the network and credentials are correct, await client.db("admin").command({ ping: 1 }) confirms that the driver has a working session.

Recognize common errors

Symptom Likely layer Action
Connection or server-selection timeout Route, listener, firewall or wrong port Resolve the hostname, inspect net.bindIp, verify the service port and allow traffic only from the application network.
Authentication failed Credentials, authentication database or mechanism Check the exact username and password, set the correct authSource, and use the mechanism enabled for that user.
TLS certificate not trusted Missing or incorrect CA trust Provide the issuing CA with tlsCAFile or install it in the platform trust store; verify the chain.
TLS hostname mismatch URI hostname does not match the certificate Use a DNS name covered by the certificate or issue a certificate containing the correct name.
Certificate expired Certificate lifecycle Renew and deploy the certificate, then restart or reload the components according to the MongoDB setup.
Permission denied reading certificate files Operating-system file permissions Grant the Node.js service account read access to the CA and client-key files without making them world-readable.
Works locally but not from the app VPS Different network path or firewall policy Test from the application host itself; compare private routes, security-group rules and the address MongoDB is bound to.

Keep secrets, certificates and logs safe

  • Inject MONGODB_URI at deployment time instead of writing it into a repository, image layer or shell history.
  • Redact credentials from error logs, health-check output and support bundles. A driver error can be logged without printing the full URI.
  • Restrict read permissions on CA and client-key files to the service account.
  • Use private networking or a VPN for cross-VPS traffic whenever available.
  • Apply MongoDB and operating-system security updates, and maintain backups and monitoring for a self-managed database.
  • Design credential rotation so the new secret can be deployed, tested with a ping, and then made exclusive without an unplanned outage.

Self-managed MongoDB on a VPS versus a managed deployment

The Node.js side can remain almost identical because the official driver uses the same MongoClient model. The operational responsibilities differ:

Concern MongoDB on your VPS Managed MongoDB deployment
Patching Your team schedules and applies database and operating-system updates. The provider supplies its own maintenance process; you still need to understand maintenance windows and compatibility.
Backups and recovery You configure backups, retention, restore tests and storage protection. The service may provide backup features, but retention, restore testing and recovery objectives remain your responsibility.
Monitoring You monitor the process, disk, memory, connections, logs and replication or storage health. The provider exposes service metrics and alerts, while application-level monitoring remains yours.
Network controls You manage net.bindIp, VPS firewalls, private routes and security groups. You configure the provider’s network allowlists, private links or equivalent controls.
TLS and certificates You may need to distribute CA files, renew certificates and protect client keys. The provider may simplify server certificates, but client trust and any application certificates still need correct configuration.
Scaling You plan CPU, memory, disk I/O, storage growth and topology changes. The provider supplies scaling controls or tiers, subject to its limits and pricing.
Total cost You pay for VPS resources, storage, backups, operations and engineering time. You pay the service price and any network or backup charges in exchange for less infrastructure work.

Whichever deployment you choose, keep the application configuration portable: one secret URI, one shared client and explicit timeout and TLS settings. Only the host, credentials and deployment-specific options should change.

A practical deployment checklist

  • Driver: mongodb is installed and locked in the application dependencies.
  • URI: host, port, application database, credentials, authSource and mechanism are correct.
  • Network: the hostname resolves from the application VPS, MongoDB listens on the reachable interface, and the firewall allows only the required source.
  • Authentication: a dedicated least-privilege account exists and administrator credentials are not used by the app.
  • TLS: encryption is enabled when required, certificates validate normally, and no insecure bypass flag is enabled in production.
  • Lifecycle: the process pings MongoDB at startup, reuses one client, reports failures without secrets, and closes the client on shutdown.
  • Operations: backups, updates, monitoring and credential rotation have an owner and a tested procedure.

What a successful connection looks like

On startup, the process reads the secret URI, establishes a session within the configured timeout, authenticates the application user, and receives a successful ping. Requests then use collections through the shared database handle. If the process receives SIGTERM, it stops accepting new work, closes the MongoDB client and exits cleanly. That sequence gives you a useful boundary: network and authentication failures appear at startup, while application queries remain focused on application behavior rather than repeatedly creating connections.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.