I am trying to connect to mongodb atlas from firebase functions like.
export default async () => {
try {
const url = 'mongodb+srv://foo:bar@foo-cluster.mongodb.net/my-db?retryWrites=true';
const client = await MongoClient.connect(url);
client.dbName('my-db');
return client;
} catch (e) {
throw e;
}
}
However, I am getting this error:
{ "code": "ESERVFAIL", "errno": "ESERVFAIL", "syscall": "querySrv", "hostname": "_mongodb._tcp.foo-cluster.mongodb.net" }
- I made sure that my firebase plan is set to Blaze so I can connect to any client outside of google network.
- I whitelisted the functions' IP in mongodb atlas dashboard, I also added "connect from everywhere" just to make sure.
- I am using nodejs mongo driver version
^3.1.0-beta4
Any thoughts? Thanks.
To solve this issue, i did:
Outbound Networks Requests are free up to 5gb/month. So just enable billing and enjoy.
More info about billing here. https://firebase.google.com/pricing#blaze-calculator
In my case, the network access rules of my mongodb atlas cluster didn't allow firebase function to access the database.
There are few caveats when connecting to Atlas from Firebase Function. Below is the correct way to return a connected client instance for further use in your FB function:
Explanation:
reportedly, you cannot connect to Atlas if you are on a Spark plan. Make sure you upgrade to Blaze if you didn't yet.
uri
string – You should not use the shortened url format when connecting to Atlas from Firebase. For some reason, only the older, long url format works reliably from firebase.client
variable – You should define theclient
variable outside the export scope, and then assign the connected client instance to it inside the function, only if it is not already assigned. This will prevent reconnecting the client on every function invocation. Firebase functions are stateless, but not entirely. they only get shut down after some period of inactivity. This means that the connection will persist for some time. From docs: If you declare a variable in global scope, its value can be reused in subsequent invocations without having to be recomputed.