Guide on establishing a connection between Firebase Cloud Functions and MongoDB Atlas

I am currently attempting to connect to a MongoDB Atlas database from cloud functions by following the guidance provided in this answer.

The code snippet I am using is as follows:

import { MongoClient } from 'mongodb'

const uri = 'mongodb://<USER>:<PASSWORD>@foo-shard-00-00-xxx.gcp.mongodb.net:27017,foo-shard-00-01-xxx.gcp.mongodb.net:27017,foo-shard-00-02-xxx.gcp.mongodb.net:27017/test?ssl=true&replicaSet=FOO-shard-0&authSource=admin&retryWrites=true'

let client

export default async () => {

    if (client && client.isConnected()) {
        console.log('DB CLIENT ALREADY CONNECTED')

    } else try {
        client = await MongoClient.connect(uri, { useNewUrlParser: true })
        console.log('DB CLIENT RECONNECTED')
    }

    catch (e) {
    throw e
    }

    return client
}

Subsequently, I have a function structured in this manner:

export const myFunction = functions.region('europe-west1').https.onRequest((request, response) => {
console.log(client.isConnected());
});

When running firebase serve locally, I am not seeing 'DB CLIENT ALREADY CONNECTED' or 'DB CLIENT RECONNECTED' messages, indicating that the anonymous function is not being called. Additionally, attempting to access the client variable inside myFunction results in an error.

As I am currently learning Node, any assistance with this issue would be greatly appreciated. Thank you.

Answer №1

Executing code in Cloud Functions requires explicit invocation. Declaring or exporting a function without calling it will not automatically run the code. To run code globally, either avoid wrapping it in a function or ensure the function is called at the global scope.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

If the sub-document exists, update it; if not, insert it using Mongoose

I am facing a challenge with adding new data to my schema. The structure of my schema is as follows: { "_id" : ObjectId("590aa0e68d4b23760d8d0e50"), "updatedAt" : ISODate("2017-05-08T07:03:08.314Z"), "createdAt" : ISODate("1987-12-31T16:00:00.000Z"), "Ava ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Create a dynamic HTML table in React by leveraging arrays

I am working with two arrays: headings=['title1','title2'] data=[['A','B'],['C','D']] How can I efficiently convert this data into an HTML table that is scalable? title1 title2 A B ...

Introducing Vee Validate 3.x and the ValidationFlags data type definition

I'm currently struggling to locate and utilize the ValidationFlags type within Vee-Validate 3. Despite my efforts, I am encountering difficulties in importing it. I am aware that this type is present in the source code located here. However, when I a ...

`Exit out of the current tab and navigate back to the parent tab`

Looking to add a link on a webpage that will specifically close the active tab in a browser without affecting other tabs. Upon clicking the close link, the user should receive an alert message prompting them to confirm with two options: "YES" and "NO". If ...

Troubleshooting a problem with the skybox texture in Three.js

I am currently experimenting with creating a basic Skybox using Three.js, but I've encountered an issue where the texture I'm applying to the cube is only visible on the outside and not on the inside. Below is the code for my skybox: const path ...

What could be the reason that angularjs html template requests aren't appearing in the top websites when viewed in a

After referring to the link , I discovered a way to determine which programming tools different sites use for application development. However, when I debug HTTP requests using Firebug, I noticed that HTML requests are not explicitly shown in the log. Alt ...

Step-by-step guide on eliminating the modal post-validation

Newbie in reactjs looking for help with modal validation issue. Goal: Press submit button inside modal, validate, then close the modal. Want to reuse modal for another row. Problem: I'm having trouble making the function work for a new row after ...

A proven method for distinguishing between desktop and mobile browsers

Similar Question: Exploring Browser Detection Methods in Javascript I am interested in finding an efficient way to differentiate between desktop and mobile browsers, either using JavaScript or PHP. if (desktop browser) { do x; } else { // mobi ...

What could be the reason for the failure of the .is(":hover") method?

Here is some code I'm using to fade out certain elements on a webpage if the mouse hasn't moved for a period of time: idleTime = 0; var idleInterval = setInterval(function() { idleTime++; if (idleTime > 1) { var isHovered = $ ...

Using Vue JS to set a default value in a custom radio group

Recently, I attempted to implement a default value in a custom radio component that I developed. Below is the code snippet: <template> <div class="custom-radio-button"> {{value}} <div v-for= "item in localValue"> <input type ...

What is the best way to thoroughly uninstall Ionic and Cordova from an Ubuntu system?

Is there a way to completely remove Cordova and Ionic 1 and all of their dependencies from my Ubuntu system? And how can I reinstall them again? I found this blog helpful for installing Ionic and its dependencies: I attempted to uninstall Cordova and Ion ...

Preventing the submission of a form using jQuery until all input, radio, select, and checkbox fields are filled out

I currently have a form that includes various field types, all of which must be filled out before submission. The submit button is disabled by default and I am looking to enable it once all fields are completed. I came across examples of this feature work ...

Tips for altering dual data values in Vue

When working with Vue.JS, I encounter the following situation: data() { return { name: 'John', sentence: "Hi, my name is {{ name }}", }; }, In my HTML file, I have the following line: <h2>{{ sentence}}</h2> ...

A guide on transferring radio button values to another program and saving them into a database with the help of PHP and jQuery

I have encountered an issue with storing radio button values in a database. Specifically, I want to assign the value of 1 for "Yes" and 0 for "No". To accomplish this, I am utilizing two scripts - a.php and b.php. The former obtains the radio button values ...

Issue in Vue.js: Struggling to compile SASS styles for an HTML element generated dynamically

I'm working with a basic Vue.js component where I'm rendering a snippet of HTML: ... <div class="sml-button" v-on:click="toggleButton()" v-html="button"></div> ... When the button is clicked, the toggleButton() function updates the ...

Tips for Troubleshooting External Evaluation Scripts

For a specific example, take a look at the haystack.js script from How Big is Your Haystack? I've been searching for a solution and it seems that using the //# sourceURL=name.js comment is the way to go. However, I am struggling with the process of a ...

`Some Items Missing from Responsive Navigation Menu`

Hey there! I'm currently diving into the world of responsive design and I'm attempting to create a navigation bar that transforms into a menu when viewed on a mobile device or phone. Everything seems to be working fine, except that not all the na ...

The Heroku Node.js application encountered an issue when trying to apply the style due to an incompatible MIME

As a complete beginner in Node.js and Express, I am encountering some errors from the console. When trying to load my CSS file from '', I receive the following error: "Refused to apply style because its MIME type ('text/html') i ...

A JavaScript function that instantiates an object that invokes its own function

Currently, I am working on an Angular service that is meant to return a new object. Everything seems to be fine and in working order. When I use new MakeRoll(), it successfully creates an instance. However, the issue arises when I call self.add towards th ...