Powell Quiring
Powell Quiring

Reputation: 2464

Node, Mongoose connection to IBM Bluemix Compose for Mongodb

How do you use Mongoose: https://github.com/Automattic/mongoose ?

The example here: https://github.com/IBM-Bluemix/compose-mongodb-helloworld-nodejs worked great. Here is a simplified snippet of the example mongo code:

MongoClient.connect(credentials.uri, { // step 1: connect
    mongos: {...},
    function(err, db) {
        if (err) {
            console.log(err);
        } else {
            mongodb = db.db("examples"); // step 2: create or use database
        }
    }
);

I can not find a mongoose example that uses a two step connection process.

I noticed that Compose for Mongodb does not support a direct connect to the existing examples database. Connecting to this url:

mongodb://admin:[email protected]:22601,bluemix...0.dblayer.com:22601/examples'

results in 'MongoError: authentication fail'

Upvotes: 0

Views: 1079

Answers (2)

cmd
cmd

Reputation: 11841

Neither Frederic's code snippet (uses Mongo driver), nor the source code he linked (connects to admin db) enable one to use mongoose to connect to a custom MongoDB.

In order to connect to a custom db with mongoose IBM Compose, you must provide a different connection string than the default provided by Compose.

The following connection string template works:

var connectionUrl = 'mongodb://<username>:<password>@<hostname>:<port>,<hostname-n>:<port-n>/<db-name>?ssl=true&authSource=admin';

with the following options:

var sslCA = [fs.readFileSync('mongo.cert')];
var options = {
  ssl: true,
  sslValidate: true,
  sslCA,
};

I've provided the complete working example on Github

Upvotes: 1

Frederic Lavigne
Frederic Lavigne

Reputation: 734

Here is an excerpt from a sample that was using Compose for MongoDB and Mongoose:

var mongoDbUrl, mongoDbOptions = {};
var mongoDbCredentials = appEnv.getServiceCreds("mycomposedb").credentials;
var ca = [new Buffer(mongoDbCredentials.ca_certificate_base64, 'base64')];
mongoDbUrl = mongoDbCredentials.uri;
mongoDbOptions = {
  mongos: {
    ssl: true,
    sslValidate: true,
    sslCA: ca,
    poolSize: 1,
    reconnectTries: 1
  }
};
console.log("Connecting to", mongoDbUrl);
mongoose.connect(mongoDbUrl, mongoDbOptions); // connect to our database

Then you can switch database with useDb.

The full source code is here

Upvotes: 1

Related Questions