Samuel Heredia
I like to believe that I can contribute to creating a better world with the developments I make :)
Templates by Samuel Heredia
Daily news aggregation with Perplexity AI & MongoDB storage
This workflow contains community nodes that are only compatible with the self-hosted version of n8n. Workflow: Daily News Aggregator & MongoDB Storage This workflow is designed to run seamlessly in the background, automating the full cycle of news aggregation, storage, and reporting with precision and reliability. Daily Trigger (Cron Node) The process kicks off every morning at 8:00 AM UTC. This scheduling ensures that fresh global news is captured consistently at the start of each day. Perplexity Node At the heart of the workflow, a Perplexity node queries the latest global news. The prompt specifies both the type of news and the JSON structure required, guaranteeing the output is ready for structured storage. The result is a clean feed of headlines, timestamps, sources, and URLs. Data Formatting (Code Node) Since Perplexity’s response is a string, the workflow includes a custom JavaScript function to clean and parse it into a valid JSON array. Each news item is then transformed into its own object, ready for iteration. MongoDB Insertion (Loop Node) Each news article is inserted into the daily_news collection in MongoDB. The workflow ensures that fields such as headline, timestamp, source, URL, and category are stored neatly, with additional metadata available for future filtering and analysis. Aggregation & Notification Prep (Code Node) Once all items are stored, the workflow aggregates the day’s results. This step prepares a digest of what was successfully processed, ensuring visibility into the pipeline’s performance. Email Notification (Gmail Node) Finally, a summary email is sent via Gmail. This message confirms the operation’s success and provides a quick snapshot of the news collected and stored that day. Workflow Flow Cron Trigger → Perplexity API → Format Data → MongoDB Insert → Aggregate Results → Send Email Notification This setup transforms what could be a manual, repetitive task into a streamlined daily routine. It not only guarantees timely and structured storage of news but also provides immediate confirmation, making it an elegant solution for automated information management.
Create a secure MongoDB data retrieval API with input validation and HTTP responses
Data Extraction from MongoDB Overview This workflow exposes a public HTTP GET endpoint to read all documents from a MongoDB collection, with: Strict validation of the collection name Error handling with proper 4xx codes Response formatting (e.g., _id → id) and a consistent 2XX JSON envelope Workflow Steps Webhook Trigger: A public GET endpoint receives requests with the collection name as a parameter. The workflow begins with a webhook that listens for incoming HTTP GET requests. The endpoint follows this pattern: https://{{your-n8n-instance}}/webhook-test/{{uuid>}}/:nameCollection The :nameCollection parameter is passed directly in the URL and specifies the MongoDB collection to be queried. Example: https://yourdomain.com/webhook-test/abcd1234/orders would attempt to fetch all documents from the orders collection. Validation: The collection name is checked against a set of rules to prevent invalid or unsafe queries. Before querying the database, the collection name undergoes validation using a regular expression: ^(?!system\.)[a-zA-Z0-9._]{1,120}$ Purpose of validation: Blocks access to MongoDB’s reserved system.* collections. Prevents injection attacks by ensuring only alphanumeric characters, underscores, and dots are allowed. Enforces MongoDB’s length restrictions (max 120 characters). This step ensures the workflow cannot be exploited with malicious input. Conditional Check: If the validation fails, the workflow stops and returns an error message. If it succeeds, it continues. The workflow checks if the collection name passes validation. If valid ✅: proceeds to query MongoDB. If invalid ❌: immediately returns a structured HTTP 400 response, adhering to RESTful standards: { "code": 400, "message": "{{ $json.message }}" } MongoDB Query: The workflow connects to MongoDB and retrieves all documents from the specified collection. To use the MongoDB node, a proper database connection must be configured in n8n. This is done through MongoDB Credentials in the node settings: Create MongoDB Credentials in n8n Go to n8n → Credentials → New. Select MongoDB and Fill in the following fields: Host: The MongoDB server hostname or IP (e.g., cluster0.mongodb.net). Port: Default is 27017 for local deployments. Database: Name of the database (e.g., myDatabase). User: MongoDB username with read permissions. Password: Corresponding password. Connection Type: Standard for most cases, or Connection String if using a full URI. Replica Set / SRV Record: Enable if using MongoDB Atlas or a replica cluster. Using a Connection String (recommended for MongoDB Atlas) Example URI: mongodb+srv://<username>:<password>@cluster0.mongodb.net/myDatabase?retryWrites=true&w=majority Paste this into the Connection String field when selecting "Connection String" as the type. Verify the Connection After saving, test the credentials to confirm n8n can connect successfully to your MongoDB instance. Configure the MongoDB Node in the Workflow Operation: Find (to fetch documents). Collection: Dynamic value passed from the workflow (e.g., {{$json["nameCollection"]}}). Query: Leave empty to fetch all documents, or define filters if needed. Result: The MongoDB node will retrieve all documents from the specified collection and pass the dataset as JSON to the next node for processing. Data Formatting: The retrieved documents are processed to adjust field names. By default, MongoDB returns its unique identifier as _id. To align with common API conventions, this step renames _id → id. This small transformation simplifies downstream usage, making responses more intuitive for client applications. Response: The cleaned dataset is returned as a structured JSON response to the original request. The processed dataset is returned as the response to the original HTTP request. Clients receive a clean JSON payload with the expected format and renamed identifiers. Example response: [ { "id": "64f13c1e2f1a5e34d9b3e7f0", "name": "John Doe", "email": "john@example.com" }, { "id": "64f13c1e2f1a5e34d9b3e7f1", "name": "Jane Smith", "email": "jane@example.com" } ] Workflow Summary Webhook (GET) → Code (Validation) → IF (Validation Check) → MongoDB (Query) → Code (Transform IDs) → Respond to Webhook Key Benefits ✅ Security-first design: prevents unauthorized access or injection attacks. ✅ Standards compliance: uses HTTP status codes (400) for invalid requests. ✅ Clean API response: transforms MongoDB’s native _id into a more user-friendly id. ✅ Scalability: ready for integration with any frontend, third-party service, or analytics pipeline.
Process contact form submissions with validation and MongoDB storage
This n8n workflow securely processes contact form submissions by validating user input, formatting the data, and storing it in a MongoDB database. The flow ensures data consistency, prevents unsafe entries, and provides a confirmation response back to the user. Workflow Form Submission Node Purpose: Serves as the workflow’s entry point. Functionality: Captures user input from the contact form, which typically includes: name last name email phone number Code Node (Validation Layer) Purpose: Ensures that collected data is valid and secure. Validations performed: Removes suspicious characters to mitigate risks like SQL injection or script injection. Validates the phone_number field format (numeric, correct length, etc.). If any field fails validation, the entry is marked as “isnotvalid” to block it from database insertion. Edit Fields Node (Data Formatting) Purpose: Normalizes data before database insertion. Transformations applied: Converts field names to snakecase (*firstname, lastname, phonenumber*). Standardizes field naming convention for consistency in MongoDB storage. MongoDB Node (Insert Documents) Purpose: Persists validated data in MongoDB Atlas. Process: Inserts documents into the target collection with the cleaned and formatted fields. Connection is established securely using a MongoDB Atlas connection string (URI). 🔧 How to Set Up MongoDB Atlas Connection URL a. Create a Cluster b. Log in to MongoDB Atlas and create a new cluster. c. Configure Database Access: Add a database user with a secure username and password, Assign appropriate roles (e.g., Atlas Admin for full access or Read/Write for limited). d. Obtain Connection String (URI) From Atlas, go to Clusters → Connect → Drivers. Copy the provided connection string, which looks like: mongodb+srv://<username>:<password>@cluster0.abcd123.mongodb.net/myDatabase?retryWrites=true&w=majority Configure in n8n In the MongoDB node, paste the URI. Replace <username>, <password>, and myDatabase with your actual credentials and database name. Test the connection to ensure it is successful. Form Ending Node Purpose: Provides closure to the workflow. Functionality: Sends a confirmation response back to the user, indicating that their contact details were successfully submitted and stored. ✅ Result: With this workflow, all contact form submissions are safely validated, normalized, and stored in MongoDB Atlas, ensuring both data integrity and security basic.