Cloud NoSQL Databases
Course: Advancing Database Topics I
MongoDB
MongoDB Atlas is a fully managed cloud database platform, designed for developers looking to build modern applications efficiently and agilely. Created by the team behind MongoDB, Atlas allows developers to focus on building applications instead of investing time and resources in database administration and maintenance. This DBaaS (Database as a Service) solution makes it easy to deploy, manage and scale NoSQL databases from anywhere in the world, ensuring optimal performance and global availability.
Example
First, we initialize the project with the dependencies
mkdir mongodb-atlas-app
cd mongodb-atlas-app
npm init -y
npm install express mongoose dotenv
Environment variables include the port (PORT
) and the MongoDB connection string (MONGO_URI
). This keeps sensitive information secure and separated from the code.
PORT=3000
MONGO_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
The Item
model defines the structure of our database records with fields like name
(required), description
(optional), and date
(defaults to the current timestamp). This ensures consistent and validated data.
const mongoose = require('mongoose');
const ItemSchema = new mongoose.Schema({
name: { type: String, required: true },
description: { type: String },
date: { type: Date, default: Date.now },
});
module.exports = mongoose.model('Item', ItemSchema);
We connect to MongoDB Atlas using mongoose.connect()
and the URI stored in .env
. A success message or error logs confirm the connection status, ensuring reliability for the database.
require('dotenv').config();
const mongoose = require('mongoose');
mongoose
.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB Atlas'))
.catch((err) => console.error('Error connecting to MongoDB:', err));
express.json()
is added to parse JSON data from incoming requests, allowing our app to handle payloads in API calls effectively.
const express = require('express');
const app = express();
app.use(express.json());
GET /
: A simple welcome route.POST /items
: Allows users to create new items, validate them, and save them to the database.GET /items
: Retrieves all saved items, providing a way to view data stored in MongoDB.
app.get('/', (req, res) => {
res.send('Welcome to the MongoDB Atlas App');
});
The app listens on the port specified in the .env
file. Once running, it logs a confirmation message, signaling it’s ready to accept requests.
app.listen(process.env.PORT, () => {
console.log(`Server running on port ${process.env.PORT}`);
});
Using tools like Postman, we can test endpoints by creating (POST /items
) and retrieving (GET /items
) data, ensuring the app integrates seamlessly with MongoDB Atlas.
{
"name": "Sample Item",
"description": "This is a test item."
}
Conclusion
MongoDB Atlas removes the complexity of managing database infrastructure, allowing developers to focus on building applications rather than worrying about backups, scaling, or server maintenance. Its automated features make it ideal for agile development teams. With features like horizontal scaling and global cluster distribution, MongoDB Atlas ensures that applications can grow alongside user demand. This makes it a reliable choice for businesses planning for large-scale operations.
Bibliography
MongoDB Atlas. (s/f). Google Cloud. Recuperado el 18 de diciembre de 2024, de https://cloud.google.com/mongodb?hl=es-419
Prefieres. (s/f). MongoDB Atlas. E-dea.co. Recuperado el 18 de diciembre de 2024, de https://www.e-dea.co/mongodb-atlas-base-de-datos-multicloud