keepcalculator

06 Numbers and Powers

Connect Node.js to MongoDB on a VPS

Card No. 06·12075 · Updated · Standard formula, shown below

This guide walks you through connecting a Node.js application to a MongoDB database running on a virtual private server (VPS). You’ll learn how to install MongoDB, start the service, create a database user, and connect from your Node.js code using the official driver. By the end, you’ll have a working connection string and a test script that verifies the connection.

What You’ll Need

  • A VPS with Ubuntu 20.04 or 22.04 (or similar Linux distribution) and root or sudo access.
  • Node.js and npm installed on your local machine (or on the VPS if you’re developing there).
  • Basic familiarity with the command line and SSH.

Step-by-Step

  1. SSH into your VPS
    Open a terminal and run: ssh user@your_server_ip. Replace user with your username and your_server_ip with your VPS’s IP address.
  2. Update the system packages
    Run sudo apt update and then sudo apt upgrade -y to ensure all existing packages are up to date.
  3. Install MongoDB
    MongoDB is not in the default Ubuntu repositories. Add the official MongoDB repository:
    curl -fsSL https://www.mongodb.org/static/pgp/server-6.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-6.0.gpg
    echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-6.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
    sudo apt update
    sudo apt install -y mongodb-org

    Note: The repository URL depends on your Ubuntu version. For 20.04 (focal), replace jammy with focal. For other versions, check the MongoDB docs.

  4. Start MongoDB and enable it on boot
    Run sudo systemctl start mongod to start the service, then sudo systemctl enable mongod to make it start automatically on reboot. Verify with sudo systemctl status mongod – you should see active (running).
  5. Create an admin user for MongoDB
    Open the MongoDB shell: mongosh. Then switch to the admin database and create a user:
    use admin
    db.createUser({
      user: "admin",
      pwd: "your_strong_password",
      roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
    })

    Exit the shell with exit.

  6. Enable authentication
    Edit the MongoDB config file: sudo nano /etc/mongod.conf. Find the security section (or add it) and add:
    security:
      authorization: enabled

    Save and exit, then restart MongoDB: sudo systemctl restart mongod.

  7. Create a database and user for your app
    Log back into mongosh with the admin user: mongosh -u admin -p your_strong_password --authenticationDatabase admin. Then create a dedicated database and user:
    use myappdb
    db.createUser({
      user: "appuser",
      pwd: "app_password",
      roles: [{ role: "readWrite", db: "myappdb" }]
    })

    Exit.

  8. Open MongoDB port (optional but recommended for remote connections)
    By default MongoDB listens on port 27017 on localhost. If you want to connect from your local machine, you need to bind to your VPS’s public IP and open the port in the firewall. Edit /etc/mongod.conf and change bindIp: 127.0.0.1 to bindIp: 0.0.0.0 (or your specific IP). Then restart MongoDB. Use sudo ufw allow 27017 if you use UFW. Important: Only do this if you understand the security risks – it exposes your database to the internet. A safer alternative is to use an SSH tunnel.
  9. Install the MongoDB Node.js driver
    On your local machine (or where your Node.js app is), create a new project folder and run:
    npm init -y
    npm install mongodb
  10. Write a test connection script
    Create a file named test.js with the following content:
    const { MongoClient } = require('mongodb');
    
    const uri = "mongodb://appuser:app_password@your_server_ip:27017/myappdb?authSource=myappdb";
    
    const client = new MongoClient(uri);
    
    async function run() {
      try {
        await client.connect();
        const db = client.db("myappdb");
        const collection = db.collection("test");
        await collection.insertOne({ message: "Hello from Node.js" });
        const doc = await collection.findOne({ message: "Hello from Node.js" });
        console.log("Connection successful. Found:", doc);
      } finally {
        await client.close();
      }
    }
    
    run().catch(console.dir);

    Replace app_password and your_server_ip with your actual values.

  11. Run the test
    Execute node test.js. If everything is set up correctly, you’ll see the inserted document printed. If not, proceed to the Troubleshooting section.

Common Mistakes

  • Using the wrong MongoDB version repository – The repository URL must match your Ubuntu version. Using the wrong one will cause installation errors.
  • Forgetting to enable authentication – If you skip step 6, MongoDB will accept connections without a password, which is a security risk.
  • Binding to 0.0.0.0 without a firewall – This exposes your database to the entire internet. Always configure UFW or a cloud security group to restrict access.
  • Incorrect connection string – The authSource parameter must match the database where the user was created (often admin or the app database). If you created the user in admin, use authSource=admin.
  • Using localhost in the connection string when connecting remotely – If your Node.js app is on a different machine, you must use the VPS’s public IP or hostname.

Tips

  • Use environment variables to store your connection string and password. Never hardcode credentials in your source code.
  • For production, consider using MongoDB Atlas (cloud-hosted) instead of self-managing on a VPS – it handles backups, monitoring, and scaling.
  • Regularly back up your MongoDB data using mongodump or a scheduled cron job.
  • Use a firewall that only allows connections from your app server’s IP, not from anywhere.
  • If you’re connecting from a local development machine, an SSH tunnel is a secure and simple alternative to opening the port.

Troubleshooting

  • Connection refused – Check that MongoDB is running (sudo systemctl status mongod). Also verify that the port is open: sudo netstat -tulpn | grep 27017. If it’s listening only on 127.0.0.1, you haven’t changed the bindIp correctly.
  • Authentication failed – Double-check the username, password, and authSource. If you created the user in admin, use authSource=admin in the URI. Also ensure you enabled authorization in the config file.
  • Timeout when connecting – This usually indicates a firewall blocking the port. Check UFW rules (sudo ufw status) and cloud provider security groups. Also confirm the VPS’s public IP is correct and that the server is reachable (try ping).
  • Error: Cannot connect to MongoDB after restart – Check the MongoDB logs: sudo journalctl -u mongod -n 50. Look for errors about config file syntax or permission issues.
  • MongoDB won’t start – Run sudo systemctl status mongod to see the error. Common causes: missing /var/lib/mongodb directory, permission issues, or a malformed config file. Try sudo mongod --config /etc/mongod.conf to see the error directly.

Frequently Asked Questions

Can I connect to MongoDB from a different machine than the VPS?

Yes, but you need to bind MongoDB to a non-localhost IP and open the port in the firewall. Always restrict access to your app server’s IP for security.

What is the difference between mongodb and mongosh?

mongodb is the daemon (server), while mongosh is the interactive shell. You use mongosh to run commands like creating users.

Do I need to install MongoDB on the same VPS as Node.js?

No, you can install them on separate servers. Just make sure the connection string points to the correct IP and port.

How do I secure my MongoDB connection?

Enable authentication, use a strong password, bind to a specific IP, and use a firewall. For extra security, use TLS/SSL or an SSH tunnel.

What is the default port for MongoDB?

27017. You can change it in the config file, but then you must update your connection string accordingly.

Can I use Mongoose instead of the native driver?

Yes, Mongoose is a popular ODM that wraps the native driver. The connection string is the same; you just use mongoose.connect(uri) instead.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →