Articles on: Database & Storage

How to create a MongoDB database and connect it to your application?

1. Prerequisites


To follow this tutorial, you will need:


  • Standard Plan or higher: Database management on Square Cloud is a feature available starting from the Standard plan.
  • Dashboard Access: Your access credentials for the Square Cloud platform.




2. Creating the Database Instance


  1. Access the Square Cloud Dashboard.
  2. Go to the Databases page and select the Create database option.
  3. Name your instance.
  4. Choose MongoDB from the list of available databases.
  5. Select the desired RAM and confirm the creation.
  6. After initialization, you will have access to the essential credentials: Host, Port, User, and Password.




3. Understanding SSL/TLS Certificates


MongoDB security is handled via TLS (Transport Layer Security) protocols. Square Cloud provides the necessary certificates so that your application's driver can validate the identity of both the server and the client.


In your database settings tab, you will find:


  • certificate.pem: The combined file containing the private key and the certificate. This is the main file for most drivers.
  • client-key.key and client-cert.crt: Provided separately in case your infrastructure requires distinct files for the key and the public certificate.




4. Technical Connection Configuration


In MongoDB, a secure connection is enabled via the tls parameter. When using the .pem file, you must reference it in two crucial points of the connection driver to ensure mutual validation:


  • tlsCAFile: Path to certificate.pem (Validates the server authority).
  • tlsCertificateKeyFile: Path to certificate.pem (Identifies the client).
  • tls: Must be set to true.


Connection String Example (URI)


mongodb://default:{password}@square-cloud-db-{id}.squareweb.app:{port}/tls=true&tlsCAFile=./certificate.pem&tlsCertificateKeyFile=./certificate.pem




Code Connection Examples


If your connection uses separate data files, just follow the examples below:


  • Python Example:


from pymongo import MongoClient

url_conexao = "mongodb://default:{password}@square-cloud-db-{id}.squareweb.app:{port}"

client = MongoClient(
url_conexao,
tlsCertificateKeyFile="certificate.pem",
tlsCAFile="certificate.pem"
)


  • JavaScript Example:


import { MongoClient } from "mongodb";
import fs from "fs";

const uri = "mongodb://default:{password}@square-cloud-db-{id}.squareweb.app:{port}";

const client = new MongoClient(uri, {
tls: true,
tlsCertificateKeyFile: "certificate.pem",
tlsCAFile: "certificate.pem",
});




5. Best Practices and Security


  • .gitignore File: The certificate.pem file is a security credential. Add it to your .gitignore immediately to prevent leaks in repositories.




Extra


For a better visual guide, watch our video tutorial: https://www.youtube.com/watch?v=K9-J6-PO3QU

Updated on: 05/19/2026

Was this article helpful?

Share your feedback

Cancel

Thank you!