Mongoose でセカンダリにアクセス可能な接続を設定をするには

January 14, 2013

MongoDB でレプリケーションセットを構成する。MongoDBでは Secondary サーバへのアクセスを読み取りであってもデフォルトで拒否するようになっている。
このためには接続ごとに slaveOk フラグを立てる必要があるが、そのときの Mongoose の設定に手間取ったのでメモしておく。

(2013/1/18 に、レプリケーション設定に誤りがあったため以降の内容を修正しています。)

オプション設定

mongoose の connection を生成する方法は色々とありますが、createConnection メソッドを使っています。
createConnection の第2引数のオプションには、それぞれ以下のキーで設定を構成できます。

接続を生成する関数例

以下、sampledb というデータベースに localhost で 27017 と 27018 ポートで動いている二つの MongoDB サーバに接続するときのサンプルです。レプリケーションセット名は「myrepl」で、コネクションプールもデフォルトの 5 から 10 に増やしています。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const DB_HOST = "localhost:27017";
const DB_NAME = "sampledb";
const DB_REPLSET_NAME = "myrepl";
const DB_REPLSET_MEMBERS = "localhost:27017,localhost:27018"

var mongoose = require('mongoose');

var mongooseConnection = (function(){
var uri;
var opts = {
server: { poolSize: 10, auto_reconnect: true }
};

if (DB_REPLSET_NAME && DB_REPLSET_MEMBERS) {
var rsmembers = DB_REPLSET_MEMBERS.split(',');

var svs = [];
rsmembers.forEach(function(sv){
svs.push("mongodb://" + sv + "/" + DB_NAME);
});
uri = svs.join(",");

opts.replset = { rs_name: DB_REPLSET_NAME, readPreference: 'primaryPreferred' };
} else {
opts.db = { slave_ok: true };
uri = 'mongodb://' + DB_HOST + '/' + DB_NAME;
}

return mongoose.createConnection(uri, opts);
})();

※ DB_REPLSET_NAME, DB_REPLSET_MEMBERS が設定されていればレプリケーション設定になります。

Node.js MongoDB Mongoose

tilfin freelance software engineer