Connecting to MongoDB using Mongoose

You can connect to a database from your build service in exactly the same way that you would within your regular Node.js code. Lets say for example that you wanted to create a build service which connects to a mongodb database using mongoose:

1. Run api init in an empty directory and accept the defaults

This will create the following folder structure:

├── endpoints
│   └── helloWorld.js
├── package.json
└── readme.md

2. Install mongoose

npm install mongoose --save

This will add mongoose to your package.json

2. Edit helloWorld.js

The following code will create a new Hit every time the build service is called, then it will return with a total count of the number of hits that this service has had over time by querying the database. This is a trivial example and you would normally use our logs feature to determine these kinds of statistics, but the purpose is to show a connection to the database.

const mongoose = require('mongoose');
mongoose.Promise = Promise;
const hitCount = new mongoose.Schema({});
const Hit = mongoose.model('Hit', hitCount);

/*
 * This is a simple build demo to show a connection to a database
 *
 * Each time the service is called, it creates a new `hit`, then
 * returns with a total count of hits stored in the database.
 *
 * @returns {number} Number of times this service has been called
 */
module.exports = (data, api) => {
  mongoose.connect('mongodb://localhost/build-test', { useMongoClient: true });
  const hit = new Hit();
  hit.save().then(() => {
    Hit.count({}).then(count => {
      api.success(count);
      mongoose.disconnect();
    })
  });
};

3. Run locally

Within your build service directory on your local machine, you can run the service by using api local:

api local helloWorld

If all worked correctly, you should see an incrementing count each time you call it.

4. Deploy!

Deploying your service is as simple as running the following:

api deploy

This will upload the code to us and make it runnable via:

api run <service-name> helloWorld

The code for this example is available on github: https://github.com/build-services/db-mongoose