使用node.js访问MongoDB
如果使用Mongodb客户端进行连接的话
使用cfenv,在本地环境中通过vcap-local.json读取服务资格证书,在CF容器环境中通过环境变量获取证书信息的代码。完整的代码可以在https://github.com/IBM-Bluemix/compose-mongodb-helloworld-nodejs/blob/master/server.js中找到。
//var appenv = cfenv.getAppEnv();
var vcapLocal = require("./vcap-local.json");
var appEnvOpts = vcapLocal ? { vcap: vcapLocal} : {}
//var appenv = cfenv.getAppEnv();
var appenv = cfenv.getAppEnv(appEnvOpts);
如果使用Mongoose进行连接
在本地环境中,同样需要使用vcap-local.json文件来读取服务凭证信息,在容器环境中,需要使用环境变量来导入这些凭证信息。连接成功后,将显示数据库列表。
#!/usr/bin/env node
var mongoose = require('mongoose');
var assert = require('assert');
var cfenv = require("cfenv");
var svc = 'compose-for-mongodb';
var vcapLocal = require("./vcap-local.json");
var appEnvOpts = vcapLocal ? { vcap: vcapLocal} : {};
var appenv = cfenv.getAppEnv(appEnvOpts);
var services = appenv.services;
var mongodb_services = services["compose-for-mongodb"];
var credentials = mongodb_services[0].credentials;
var ca = [new Buffer(credentials.ca_certificate_base64, 'base64')];
var options = {
mongos: {
ssl: true,
sslValidate: true,
sslCA: ca,
poolSize: 1,
reconnectTries: 1
}
};
// コールバック エラー時
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
// コールバック セッション確立時
mongoose.connection.on('open', function (err) {
console.log("=== Connected to mongodb on Compose ===" );
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);
});
});
// 接続
mongoose.connect(credentials.uri, options);
vcap-local.json -> 本地的vcap.json配置文件
在Bluemix门户上,将credentials部分替换为显示的服务资格信息进行使用。
imac:mongodb_mongoose maho$ cat vcap-local.json
{
"services": {
"compose-for-mongodb": [
{
"credentials": {
"ca_certificate_base64": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURlekNDQW1PZ0F3SUJBZ0lFV1ZOZ0tEQU5CZ2txaGtpRzl3MEJBUTBGQURBL01UMH
<省略>
RkpObnVXQ01Fa2lZdVZoZDJoN21nekFVM2VlNVV3bmF6WHRlQT09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K",
"db_type": "mongodb",
"deployment_id": "******************:",
"maps": [],
"name": "**************************",
"uri": "mongodb://*****:***********@sl-us-south-1-portal.3.dblayer.com:17599,sl-us-south-1-portal.4.dblayer.com:17599/admin?ssl=true",
"uri_cli": "mongo --ssl --sslAllowInvalidCertificates sl-us-south-1-portal.3.dblayer.com:17599/admin -u admin -p ***************"
},
"label": "compose-for-mongodb",
"name": "Compose for MongoDB-no",
"plan": "Standard",
"provider": null,
"syslog_drain_url": null,
"tags": [
"big_data",
"data_management",
"ibm_created"
],
"volume_mounts": []
}
]
}
}
总结
使用Mongodb时,我担心无法在本地环境中连接,但问题已经解决了。太好了(笑)
请提供相关资料
-
- Mongoose, Node and Compose https://help.compose.com/docs/connecting-to-mongodb#section-nodejs-native
GitHub IBM-Bluemix/compose-mongodb-helloworld-nodejs https://github.com/IBM-Bluemix/compose-mongodb-helloworld-nodejs
Hosted MongoDB https://www.compose.com/mongodb