'use strict'; (function(module) { var winston = require('winston'), async = require('async'), nconf = require('nconf'), express = require('express'), db, mongoClient, mongoStore; try { mongoClient = require('mongodb').MongoClient; mongoStore = require('connect-mongo')(express); } catch (err) { winston.error('Unable to initialize MongoDB! Is MongoDB installed? Error :' + err.message); process.exit(); } module.init = function(callback) { mongoClient.connect('mongodb://'+ nconf.get('mongo:host') + ':' + nconf.get('mongo:port') + '/' + nconf.get('mongo:database'), function(err, _db) { if(err) { winston.error("NodeBB could not connect to your Mongo database. Mongo returned the following error: " + err.message); process.exit(); } db = _db; module.client = db; module.sessionStore = new mongoStore({ db: db }); if(nconf.get('mongo:password') && nconf.get('mongo:username')) { db.authenticate(nconf.get('mongo:username'), nconf.get('mongo:password'), function (err) { if(err) { winston.error(err.message); process.exit(); } createIndices(); }); } else { winston.warn('You have no mongo password setup!'); createIndices(); } function createIndices() { db.collection('objects').ensureIndex({_key :1}, {background:true}, function(err) { if(err) { winston.error('Error creating index ' + err.message); } }); db.collection('objects').ensureIndex({'expireAt':1}, {expireAfterSeconds:0, background:true}, function(err) { if(err) { winston.error('Error creating index ' + err.message); } }); db.collection('search').ensureIndex({content:'text'}, {background:true}, function(err) { if(err) { winston.error('Error creating index ' + err.message); } }); if(typeof callback === 'function') { callback(); } } }); }; module.close = function() { db.close(); }; // // helper functions // function findItem(data, key) { if(!data) { return null; } for(var i=0; i= 0) || (start >= 0 && stop < 0)) { skip = 0; limit = Math.pow(2, 31) - 2; splice = true; } else if (start > stop) { return callback(null, []); } db.collection('objects').findOne({_key:key}, { array: { $slice: [skip, limit] }}, function(err, data) { if(err || !(data && data.array)) { return callback(err, []); } if(splice) { if(start < 0) { start = data.array.length - Math.abs(start); } if(stop < 0) { stop = data.array.length - Math.abs(stop); } if(start > stop) { return callback(null, []); } var howMany = stop - start + 1; if(start !== 0 || howMany !== data.array.length) { data.array = data.array.splice(start, howMany); } } callback(null, data.array); }); }; }(exports));