Edit on GitHub
Report issue
Page history

Submitted by @{[ TutorialCtrl.tutorial.github_username ]} {[ TutorialCtrl.tutorial.date_published | date:'mediumDate' ]}

title: Connect to MongoDB from Node.js on Google App Engine Flexible Environment description: Learn how to connect to MongoDB from a Node.js app running on Google App Engine flexible environment. author: jmdobry tags: App Engine, Node.js, MongoDB date_published: 2017-11-02


MongoDB

MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need

– mongodb.com

You can check out Node.js and Google Cloud Platform to get an overview of Node.js itself and learn ways to run Node.js apps on Google Cloud Platform.

Prerequisites

  1. Create a project in the Google Cloud Platform Console.
  2. Enable billing for your project.
  3. Install the Google Cloud SDK.
  4. Prepare your environment for Node.js development

Create a MongoDB database

There are multiple options for creating a new MongoDB database. For example:

  • Create a Google Compute Engine virtual machine with MongoDB pre-installed.
  • Use mLab to create a free MongoDB deployment on Google Cloud Platform.

Prepare the app

  1. Initialize a package.json file with the following command:

    npm init
    
  2. Install dependencies:

    npm install --save mongodb nconf
    
  3. Create a server.js file with the following contents:

    'use strict';
    
    const mongodb = require('mongodb');
    const http = require('http');
    const nconf = require('nconf');
    
    // Read in keys and secrets. Using nconf use can set secrets via
    // environment variables, command-line arguments, or a keys.json file.
    nconf.argv().env().file('keys.json');
    
    // Connect to a MongoDB server provisioned over at
    // MongoLab.  See the README for more info.
    
    const user = nconf.get('mongoUser');
    const pass = nconf.get('mongoPass');
    const host = nconf.get('mongoHost');
    const port = nconf.get('mongoPort');
    
    let uri = `mongodb://${user}:${pass}@${host}:${port}`;
    if (nconf.get('mongoDatabase')) {
      uri = `${uri}/${nconf.get('mongoDatabase')}`;
    }
    console.log(uri);
    
    mongodb.MongoClient.connect(uri, (err, db) => {
      if (err) {
        throw err;
      }
    
      // Create a simple little server.
      http.createServer((req, res) => {
        if (req.url === '/_ah/health') {
          res.writeHead(200, {
            'Content-Type': 'text/plain'
          });
          res.write('OK');
          res.end();
          return;
        }
        // Track every IP that has visited this site
        const collection = db.collection('IPs');
    
        const ip = {
          address: req.connection.remoteAddress
        };
    
        collection.insert(ip, (err) => {
          if (err) {
            throw err;
          }
    
          // push out a range
          let iplist = '';
          collection.find().toArray((err, data) => {
            if (err) {
              throw err;
            }
            data.forEach((ip) => {
              iplist += `${ip.address}; `;
            });
    
            res.writeHead(200, {
              'Content-Type': 'text/plain'
            });
            res.write('IPs:\n');
            res.end(iplist);
          });
        });
      }).listen(process.env.PORT || 8080, () => {
        console.log('started web process');
      });
    });
    
  4. Create a keys.json file with the following content, replacing the variables with your own values:

    {
      "mongoHost": "YOUR_MONGO_HOST",
      "mongoPort": "YOUR_MONGO_PORT",
      "mongoDatabase": "YOUR_MONGO_DB",
      "mongoUser": "YOUR_MONGO_USERNAME",
      "mongoPass": "YOUR_MONGO_PASSWORD"
    }
    

    Do not check your credentials into source control. Create a .gitignore file if you don't have one, and add keys.json to it.

Run the app

  1. Run the app locally:

    npm start
    
  2. Visit http://localhost:8080 to see the app.

Deploy the app

  1. Create an app.yaml file with the following content:

    runtime: nodejs
    env: flex
    
  2. Run the following command to deploy your app:

    gcloud app deploy
    
  3. View the deployed app:

    gcloud app browse
    
See more by @{[ TutorialCtrl.tutorial.github_username ]} and more tagged {[ tag ]}{[ $last ? '' : ', ' ]}

Submit a Tutorial

Share step-by-step guides

SUBMIT A TUTORIAL

Request a Tutorial

Ask for community help

SUBMIT A REQUEST

GCP Tutorials

Tutorials published by GCP

VIEW TUTORIALS

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies. Java is a registered trademark of Oracle and/or its affiliates.