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.