【问题标题】:Node, Mongoose connection to IBM Bluemix Compose for Mongodb节点、Mongoose 与 IBM Bluemix Compose for Mongodb 的连接
【发布时间】:2017-01-28 16:12:10
【问题描述】:

你如何使用猫鼬:https://github.com/Automattic/mongoose

此处的示例:https://github.com/IBM-Bluemix/compose-mongodb-helloworld-nodejs 效果很好。 这是示例 mongo 代码的简化 sn-p:

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
        }
    }
);

我找不到使用两步连接过程的猫鼬示例。

我注意到 Compose for Mongodb 不支持直接连接到现有示例数据库。 连接到这个网址:

mongodb://admin:PW@bluemix...4.dblayer.com:22601,bluemix...0.dblayer.com:22601/examples'

导致“MongoError:身份验证失败”

【问题讨论】:

    标签: node.js mongodb ibm-cloud compose-db


    【解决方案1】:

    以下是使用 Compose for MongoDB 和 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
    

    然后就可以用useDb切换数据库了。

    The full source code is here

    【讨论】:

      【解决方案2】:

      Frederic 的代码 sn-p(使用 Mongo 驱动程序)和他链接的源代码(连接到 admin db)都无法使用 mongoose 连接到自定义 MongoDB。

      要使用 mongoose IBM Compose 连接到自定义数据库,您必须提供与 Compose 提供的默认连接字符串不同的连接字符串。

      以下连接字符串模板有效:

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

      有以下选项:

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

      我在Github 上提供了the complete working example

      【讨论】:

        猜你喜欢
        • 2017-10-02
        • 2016-02-01
        • 2020-07-23
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        • 1970-01-01
        • 2017-02-20
        相关资源
        最近更新 更多