开发者社区> 问答> 正文

云数据库 MongoDB集群版Node.js 连接示例



相关链接


MongoDB Node.js Driver

项目初始化mkdir node-mongodb-demo
cd node-mongodb-demo
npm init





安装驱动包以及工具包npm install mongodb node-uuid sprintf-js –save




获取云数据库 MongoDB 连接信息


请查看 MongoDB 连接信息七要素获取方法

Node.js Demo Code'use strict';
var uuid = require('node-uuid');
var sprintf = require("sprintf-js").sprintf;
var mongoClient = require('mongodb').MongoClient;
var host1 = "demotest-1.mongodb.tbc3.newtest.rdstest.aliyun-inc.com";
var port1 = 27017;
var host2 = "demotest-2.mongodb.tbc3.newtest.rdstest.aliyun-inc.com";
var port2 = 27017;
var username = "demouser";
var password = "123456";
var replSetName = "mgset-1441984991";
var demoDb = "test";
var demoColl = "testColl";
// 官方建议使用的方案
var url = sprintf("mongodb://%s:%d,%s:%d/%s?replicaSet=%s", host1, port1, host2, port2, demoDb, replSetName);
console.info("url:", url);
// 获取mongoClient
mongoClient.connect(url, function(err, db) {
    if(err) {
        console.error("connect err:", err);
        return 1;
    }
    // 授权. 这里的username基于admin数据库授权
    var adminDb = db.admin();
    adminDb.authenticate(username, password, function(err, result) {
        if(err) {
            console.error("authenticate err:", err);
            return 1;
        }
        // 取得Collecton句柄
        var collection = db.collection(demoColl);
        var demoName = "NODE:" + uuid.v1();
        var doc = {"DEMO": demoName, "MESG": "Hello AliCoudDB For MongoDB"};
        console.info("ready insert document: ", doc);
        // 插入数据
        collection.insertOne(doc, function(err, data) {
            if(err) {
                console.error("insert err:", err);
                return 1;
            }
            console.info("insert result:", data["result"]);
            // 读取数据
            var filter = {"DEMO": demoName};
            collection.find(filter).toArray(function(err, items) {
                if(err) {
                    console.error("find err:", err);
                    return 1;
                }
                console.info("find document: ", items);
                //关闭Client,释放资源
                db.close();
            });
        });
    });
});



展开
收起
云栖大讲堂 2017-10-30 16:13:28 2336 0
0 条回答
写回答
取消 提交回答
问答排行榜
最热
最新

相关电子书

更多
JavaScript面向对象的程序设计 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载