Powered By GitBook
nodejs-mongodb-on-appengine
Learn how to connect to MongoDB from a Node.js app running on App Engine flexible environment.
Contributed by Google employees.
You can check out Node.js and Google Cloud to get an overview of Node.js itself and learn ways to run Node.js apps on Google Cloud.

Prerequisites

    1.
    Create a project in the Cloud Console.
    2.
    Enable billing for your project.
    3.
    Install the Cloud SDK.

Create a MongoDB database

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

Prepare the app

    1.
    Initialize a package.json file with the following command:
    1
    npm init
    Copied!
    2.
    Install dependencies:
    1
    npm install --save mongodb nconf
    Copied!
    3.
    Create a server.js file with the following contents:
    1
    'use strict';
    2
    ​
    3
    const mongodb = require('mongodb');
    4
    const http = require('http');
    5
    const nconf = require('nconf');
    6
    ​
    7
    // Read in keys and secrets. Using nconf use can set secrets via
    8
    // environment variables, command-line arguments, or a keys.json file.
    9
    nconf.argv().env().file('keys.json');
    10
    ​
    11
    // Connect to a MongoDB server provisioned over at
    12
    // MongoLab. See the README for more info.
    13
    ​
    14
    const user = nconf.get('mongoUser');
    15
    const pass = nconf.get('mongoPass');
    16
    const host = nconf.get('mongoHost');
    17
    const port = nconf.get('mongoPort');
    18
    ​
    19
    let uri = `mongodb://${user}:${pass}@${host}:${port}`;
    20
    if (nconf.get('mongoDatabase')) {
    21
    uri = `${uri}/${nconf.get('mongoDatabase')}`;
    22
    }
    23
    console.log(uri);
    24
    ​
    25
    mongodb.MongoClient.connect(uri, (err, db) => {
    26
    if (err) {
    27
    throw err;
    28
    }
    29
    ​
    30
    // Create a simple little server.
    31
    http.createServer((req, res) => {
    32
    if (req.url === '/_ah/health') {
    33
    res.writeHead(200, {
    34
    'Content-Type': 'text/plain'
    35
    });
    36
    res.write('OK');
    37
    res.end();
    38
    return;
    39
    }
    40
    // Track every IP that has visited this site
    41
    const collection = db.collection('IPs');
    42
    ​
    43
    const ip = {
    44
    address: req.connection.remoteAddress
    45
    };
    46
    ​
    47
    mongodb.MongoClient.connect(uri, { useNewUrlParser: true }, (err, client) => {
    48
    if (err) {
    49
    throw err;
    50
    }
    51
    ​
    52
    const db = client.db(nconf.get("mongoDatabase"))
    53
    ​
    54
    // push out a range
    55
    let iplist = '';
    56
    collection.find().toArray((err, data) => {
    57
    if (err) {
    58
    throw err;
    59
    }
    60
    // Track every IP that has visited this site
    61
    const collection = db.collection('IPs');
    62
    ​
    63
    const ip = {
    64
    address: req.connection.remoteAddress
    65
    };
    66
    ​
    67
    collection.insertOne(ip, (err) => {
    68
    if (err) {
    69
    throw err;
    70
    }
    71
    ​
    72
    // push out a range
    73
    let iplist = '';
    74
    collection.find().toArray((err, data) => {
    75
    if (err) {
    76
    throw err;
    77
    }
    78
    data.forEach((ip) => {
    79
    iplist += `${ip.address}; `;
    80
    });
    81
    ​
    82
    res.writeHead(200, {
    83
    'Content-Type': 'text/plain'
    84
    });
    85
    res.write('IPs:\n');
    86
    res.end(iplist);
    87
    });
    88
    });
    89
    ​
    90
    res.writeHead(200, {
    91
    'Content-Type': 'text/plain'
    92
    });
    93
    res.write('IPs:\n');
    94
    res.end(iplist);
    95
    });
    96
    });
    97
    }).listen(process.env.PORT || 8080, () => {
    98
    console.log('started web process');
    99
    });
    100
    });
    Copied!
    4.
    Create a keys.json file with the following content, replacing the variables with your own values:
    1
    {
    2
    "mongoHost": "YOUR_MONGO_HOST",
    3
    "mongoPort": "YOUR_MONGO_PORT",
    4
    "mongoDatabase": "YOUR_MONGO_DB",
    5
    "mongoUser": "YOUR_MONGO_USERNAME",
    6
    "mongoPass": "YOUR_MONGO_PASSWORD"
    7
    }
    Copied!
    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:
    1
    npm start
    Copied!
    2.
    Visit http://localhost:8080 to see the app.

Deploy the app

    1.
    Create an app.yaml file with the following content:
    1
    runtime: nodejs
    2
    env: flex
    Copied!
    2.
    Run the following command to deploy your app:
    1
    gcloud app deploy
    Copied!
    3.
    View the deployed app:
    1
    gcloud app browse
    Copied!
Last modified 7mo ago