Thursday, 21 June, 2018 UTC

Summary

This article was originally published on Code Barbarian. Thank you for supporting the partners who make SitePoint possible.

Serverless architectures are becoming increasingly popular, and with good reason. In my experience, container-based orchestration frameworks have a steep learning curve and are overkill for most consumer-facing companies. With FaaS architectures, like AWS Lambda and Azure Functions, in theory the only devops you need is bundling and uploading your app.

This article will walk you through setting up a Google Cloud Function in Node.js that connects to MongoDB. However, one major limitation of stateless functions is the need to establish a separate database connection every time the stateless function runs, which incurs a major performance penalty. Unfortunately, I haven't been able to figure out how to reuse a database connection in Google Cloud Functions, the trick that works for IBM Cloud, Azure Functions, and AWS Lambda does not work for Google Cloud Functions.

"Hello, World" in Google Cloud Functions

Go to the Google Cloud Functions landing page and click "Try it free".

Click on the hamburger icon in the upper left and find the "Cloud Functions" link in the sidebar, then click "Create function".

Name your function "hello-world" and leave the rest of the options in the "Create function" form unchanged. Leave "Function to execute" as "helloWorld", because that needs to match the name of the function your code exports. Below is the code you should enter in, so you can confirm what version of Node.js your function is running on.

Google Cloud Functions don't give you any control over what version of Node.js you run, they run Node.js v6.11.5 currently. You can't use async/await natively on Google Cloud Functions at the time of this writing.

Connecting to MongoDB Atlas

Click on the "Source" tab in the function details and hit the "Edit" button. You'll notice there's 2 files in your source code, one of which is package.json. Edit package.json to match the below code.