Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure StrongLoop LoopBack MongoDB datasource for deployment to Heroku

I'm using LoopBack ver. 1.6 and have a local mongoDB server running for development using he following datasource configuration:

  "mongodb": {
    "defaultForType": "mongodb",
    "connector": "loopback-connector-mongodb",
    "database": "xxxdbname",
    "host": "localhost",
    "port": "27017"
  },

Now I want to deploy to Heroku but I don't know how to configure the datasource to point at the MongoLab db since it has a dynamically generated connection string:

from the Heroku dox:

var mongo = require('mongodb');

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
    });
  });
});

So what kind of changes do I need to make to my datasource JSON to map the Heroku connection string?

like image 626
user2808320 Avatar asked Feb 08 '14 20:02

user2808320


2 Answers

This has now (as of June 27 2014) been addressed: create a file datasources.local.js with the following content (where mongodb is your data source name):

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

module.exports = {
  mongodb: {
    defaultForType: "mongodb",
    connector: "loopback-connector-mongodb",
    url: mongoUri
  }
};

Note: datasources.json is still required (can be empty) and the .js overrides the configuration in the .json file.

like image 195
kynan Avatar answered Nov 13 '22 17:11

kynan


This is a TODO for LoopBack to support configuration of datasources/models from environment variables and other sources. One idea is to use a template engine to load datasources.json so that it can have variables to be resolved at runtime.

Related to your question, LoopBack allows you to configure the datasource using a 'url' property. For example:

{
   "connector": "loopback-connector-mongodb",
   "url": "mongodb://localhost:27017/mydb" 
}

As a workaround, you can write a post-deployment script for Heroku to replace the url value with process.env.MONGOLAB_URI or process.env.MONGOHQ_URL.

sed -i.bak s/MONGODB_URL/$MONGOHQ_URL/g datasources.json

Meanwhile, please open an issue at https://github.com/strongloop/loopback/issues.

like image 29
Raymond Feng Avatar answered Nov 13 '22 17:11

Raymond Feng