IBM-Cloud / compose-mongodb-helloworld-nodejs

Shows you how to connect to an IBM Compose for MongoDB for IBM Cloud service using Node.js
Apache License 2.0
14 stars 13 forks source link

Mongoose example #2

Closed marius-avram closed 6 years ago

marius-avram commented 7 years ago

Would be nice to have.

marius-avram commented 7 years ago

Ok, after struggling for a lot of time I managed to connect to the database. However I'm not sure if replicas work as they should.

var mongoose = require('mongoose');
var mongodbUri = require('mongodb-uri');
var cfenv = require('cfenv');

var appenv = cfenv.getAppEnv();
var services = appenv.services;
var mongodb_services = services["compose-for-mongodb"];

module.exports.connect = function () {
  var credentials = mongodb_services[0].credentials;
  var ca = [new Buffer(credentials.ca_certificate_base64, 'base64')];

  var uri = credentials.uri;
  var mongooseConnectString = mongodbUri.formatMongoose(uri);
  var singlemongooseConnectString = mongooseConnectString.split(",")[0];

  mongoose.connect(singlemongooseConnectString, {
    server: {
      ssl: true,
      sslValidate: true,
      sslCA: ca,
      poolSize: 1,
      reconnectTries: 1
    }
  });
}
jackerman426 commented 7 years ago

MongoError: w: 'majority' is the only valid write concern when writing to config server replica sets, got: { w: 1, wtimeout: 0 }

any ideas? super frustrating

codepope commented 7 years ago

That sounds like an issue with the deployment. Contact support.

On 24 Feb 2017, at 15:06, mtzakris notifications@github.com wrote:

MongoError: w: 'majority' is the only valid write concern when writing to config server replica sets, got: { w: 1, wtimeout: 0 }

any ideas? super frustrating

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/IBM-Bluemix/compose-mongodb-helloworld-nodejs/issues/2#issuecomment-282313784, or mute the thread https://github.com/notifications/unsubscribe-auth/AAEb7IcN9C7j-PkExRPLylbjvjgKEeofks5rfvIPgaJpZM4LGmD3.

jackerman426 commented 7 years ago

When I was using a deployment through compose it was working. I changed the deployment to Compose for MongoDB withing bluemix and the url with exactly the same method in mongoose produces this error. On the other hand I can connect with tools like mongochef .

jackerman426 commented 7 years ago

The problem occurs in the mongoose findOneAndUpdate function

codepope commented 7 years ago

Ok, the mongoose.connect call is wrong as it is setting it up to connect to a single server not a pair of mangos servers.

There's no need to strip the string to a single server.

Just enclose the settings as within a mongos: { } section.

Here's the current Compose example (not on Bluemix) for Mongoose - settings on Bluemix are acquired through cf.

var mongoose = require('mongoose');
var assert = require('assert');
var fs = require('fs');

var ca = [ fs.readFileSync(__dirname + "/servercert.crt") ];

var options = {
    mongos: {
      ssl: true,
      sslValidate: true,
      sslCA: ca
    }
}

// If the connection throws an error
mongoose.connection.on('error',function (err) {
  console.log('Mongoose default connection error: ' + err);
});

mongoose.connection.on('open', function (err) {
    assert.equal(null, err);
    mongoose.connection.db.listCollections().toArray(function(err, collections) {
        assert.equal(null, err);
        collections.forEach(function(collection) {
            console.log(collection);
        });
        mongoose.connection.db.close();
        process.exit(0);
    })
});

// Let's open that connection
mongoose.connect(process.env.MONGODB_URL, options);
bancey commented 7 years ago

@mtzakris did you ever find a solution to the w: 'majority' is the only valid write concern when writing to config server replica sets, got: { w: 1, wtimeout: 0 } issue? I'm running into it now 😟

codepope commented 7 years ago

@alexbance That error occurs when you have connected but not selected a database to work with; you will find that you are writing into the "admin" database which is actually housed on the smaller config servers.

Unfortunately, Mongoose needs the database specified in the connection string. Other drivers simply let you "use" another database.

You will need to change the supplied credential - which ends /admin - and change it to, "/yourdbname?authSource=admin" to use the admin credentials, or create a new MongoDB database on the instance, add users to that and then use that.

jackerman426 commented 7 years ago

@alexbance try to pass as parameter to your mongoose queries: w: 'majority'

bancey commented 7 years ago

Thank you both, problem solved :)

ghasemikasra39 commented 7 years ago

I was absolutely terrified by this error. I did what @alexbance mentioned and my problem was fixed. Thank you so much

ManojKuppaiahSudhakara commented 6 years ago

@codepope Can you please guide me how to connect compose mongodb using ibmbluemix ..const util = require('util'); const assert = require('assert'); var cfenv = require('cfenv'); var appenv = cfenv.getAppEnv(); var services = appenv.services; var credentials = mongodb_services[0].credentials; var mongodb_services = services["compose-for-mongodb"]; var ca = [new Buffer(credentials.ca_certificate_base64, 'base64')]; var mongodb; MongoClient.connect(credentials.uri, { mongos: { ssl: true, sslValidate: true, sslCA: ca, poolSize: 1, reconnectTries: 1 } }, function(err, db) { // Here we handle the async response. This is a simple example and // we're not going to inject the database connection into the // middleware, just save it in a global variable, as long as there // isn't an error. if (err) { console.log(err); } else { // Although we have a connection, it's to the "admin" database // of MongoDB deployment. In this example, we want the // "examples" database so what we do here is create that // connection using the current connection. mongodb = db.db("IBMBLUEMIX"); } } ); Please help me with this

codepope commented 6 years ago

@ManojKuppaiahSudhakara your query is unrelated to this issue, Consult the readme for directions on use and open a new issue if you have a specific query.