Example #1
0
 function(next) {
     // Create and open the connection
     var server = new mongodb.Server(self.host, self.port, { safe:true, auto_reconnect:true }, {}),
         db = new mongodb.Db(self.db, server);
     db.open(next);
 },
Example #2
0
/**
 * Module dependencies.
 */
var _ = require('underscore')._,
    express = require('express'),
    mongodb = require('mongodb'),
    jqtpl = require('jqtpl');

var app = module.exports = express.createServer();

db = new mongodb.Db('chrono_metrics_' + app.settings.env, new mongodb.Server('localhost', 27017, {}));
db.addListener("error", function(error) {
  console.log("Error connecting to mongodb -- perhaps it isn't running?");
});


// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set("view options", {layout: false});
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.logger());
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
Example #3
0
      response.writeHead(200, "OK", {'Content-Type': 'text/html'});     
      response.end();

      console.log(resultado);
    });
});



console.log("servidor iniciado...");
//app.listen(port,host);
app.listen(process.env.VCAP_APP_PORT || 80);//3000
var mongoDB=require("mongodb");
var host=mongo.hostname;
var port=mongo.port; //Connection.DEFAULT_PORT;
var dbname=mongo.db;
console.log("host"+host);

var db=new mongoDB.Db(dbname,new mongoDB.Server(host,port));

var usuarioCol;

db.open(function(error){
  console.log("Conectado a la base de datos "+host+" "+port);

  db.collection("respuestas2",function(error,col){
    console.log("Tenemos la colección");
    usuarioCol=col;
  });
});
require.paths.unshift('../lib')

var mongodb = require('mongodb'),
    q = require('queue');

var client = new mongodb.Db('chaos-board',
    new mongodb.Server("127.0.0.1", 27017, {}));

function update (board, callback) {
  var queue = new q.Queue(function (compressed) {
    board.drawingQueue = compressed;
    callback(board);
  }, 200000000000);
  console.log(board.boardId + ":" + board.drawingQueue.length); 
  for (var i=0; i < board.drawingQueue.length; i++) {
    queue.feed(board.drawingQueue[i]);
  }
  queue.done();
}

client.open(function(err, _client) {
  client.collection('chaos', function (err, collection) {
    collection.find({}, {}, function (err, cursor) { 
      cursor.count(function (err, i) {
       console.log("have " + i); 
      });
    });

    setTimeout(function ()  {
      var i = 0;
      collection.find({}, {}, function (err, cursor) {
Example #5
0
var config = {
  db: 'achi',
  port: 27017,
  host: '127.0.0.1',
  server_config: {
    auto_reconnect: true
  },
  connector_config: {
    safe: true
  }
};

var db;
var mongodb = require("mongodb");
var mongoserver = new mongodb.Server(config.host, config.port, config.server_config);
var db_connector = new mongodb.Db(config.db, mongoserver, config.connector_config);

db_connector.open(function(err, dbs) {
  db = dbs;
});

var services = {
  'twitter': require('./qS_twitter'),
  'vkontakte': require('./qS_vkontakte'),
  'facebook': require('./qS_facebook'),
  'bitbucket': require('./qS_bitbucket'),
  'github': require('./qS_github'),
  'instagram': require('./qS_instagram'),
  'foursquare': require('./qS_foursquare'),
  'odnoklassniki': require('./qS_odnoklassniki'),
  'steam': require('./qS_steam'),
Example #6
0
var mongodb=require("mongodb");
var server=new mongodb.Server(
	"127.0.0.1",
	27017,
	{auto_reconnect:true}
);
var db=new mongodb.Db(
	"text",
	server,
	{safe:true}
);
db.open(function(err,db){
	if(err){
		console.log(err);
	}else{
		console.log("success")
		db.collection("text",{safe:true},function(err,conn){
			if(err){
				console.log(err)
			}else{
				conn.find({},{id:1,name:1,_id:0}).limit(3).skip(1).toArray(function(err,res){
					if(!err){
						res.forEach(function(value){
							console.log(value.name)
						})
					}
				});
			}
		})
	}
})
Example #7
0
 return new Promise((resolve) => {
     resolve(dbHandler.collection(objType));
 });
Example #8
0
#!/usr/bin/env node
var Db = require('mongodb').Db,
  Connection = require('mongodb').Connection,
  Server = require('mongodb').Server;
  config = require('./config.json');
require('iron-bones').load(__dirname);

var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost';
var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT;
var mongo = new Db('parks', new Server(host, port, {}));

console.log("Env: " + process.env.NODE_ENV);

if (!module.parent) {
	console.log("index initalized " + __dirname);
	mongo.open(function(err, db) {
		global.db = db;
		db.authenticate(config.dbUser, config.dbPass, function() {
		
			
		});
	});

		
    require('iron-bones').start();
}
Example #9
0
var MongoDB = require('mongodb').Db;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSONPure;

var dbPort 		= 27017;
var dbHost 		= 'localhost';
var dbName 		= 'bookshoppe';

/* establish the database connection */

var db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});

db.open(function(err, db){
    if (!err) {
        console.log("Connected to bookshoppe database");
        db.collection('subjects', {strict: true}, function(err, collection) {
            if (err) {
                console.log("The subjects collection does not exist. Creating it with sample data...");
                populateDB();
            }
        });
    }
});
var subjects = db.collection('subjects');

/* methods related to subjects */

exports.findAll = function(callback) {
    subjects.find().toArray(function(err, items) {
        console.log('subjects send from DB');
        callback(items);
Example #10
0
Db.connect(config.mongo_url, {w: 1}, function(err, db) { 
  q = async.queue(downloadGTFS, 1);
  //loop through all agencies specified
  //If the agency_key is a URL, download that GTFS file, otherwise treat 
  //it as an agency_key and get file from gtfs-data-exchange.com
  config.agencies.forEach(function(item) {
    if(typeof(item) == 'string') {
      var agency = {
              agency_key: item
            , agency_url: 'http://www.gtfs-data-exchange.com/agency/' + item + '/latest.zip'
          }
    } else {
      var agency = {
              agency_key: item.agency_key
            , agency_url: item.url
          }
    }

    if(!agency.agency_key || !agency.agency_url) {
      handleError(new Error('No URL or Agency Key provided.'));
    }

    q.push(agency);
  });

  q.drain = function(e) {
    console.log('All agencies completed (' + config.agencies.length + ' total)');
    db.close();
    process.exit();
  }


  function downloadGTFS(task, cb) {
    var agency_key = task.agency_key
      , agency_bounds = {sw: [], ne: []}
      , agency_url = task.agency_url;

    console.log('Starting ' + agency_key);

    async.series([
      cleanupFiles,
      downloadFiles,
      removeDatabase,
      importFiles,
      postProcess,
      cleanupFiles
    ], function(e, results){
      console.log( e || agency_key + ': Completed')
      cb();
    });


    function cleanupFiles(cb) {
      //remove old downloaded file
  		exec( (process.platform.match(/^win/) ? 'rmdir /Q /S ' : 'rm -rf ') + downloadDir, function(e, stdout, stderr) {
  		  try {
    			//create downloads directory
    			fs.mkdirSync(downloadDir);
    			cb();
  		  } catch(e) {
          if(e.code == 'EEXIST') {
            cb();
          } else {
            handleError(e);
          }
        }
  		});
    }
    

    function downloadFiles(cb) {
      //do download
      request(agency_url, processFile).pipe(fs.createWriteStream(downloadDir + '/latest.zip'));

      function processFile(e, response, body){
        if(response && response.statusCode != 200){ cb(new Error('Couldn\'t download files')); }
        console.log(agency_key + ': Download successful');
  	
        fs.createReadStream(downloadDir + '/latest.zip')
          .pipe(unzip.Extract({ path: downloadDir }).on('close', cb))
          .on('error', handleError);
      }
    }


    function removeDatabase(cb) {
      //remove old db records based on agency_key
      async.forEach(GTFSFiles, function(GTFSFile, cb){
        db.collection(GTFSFile.collection, function(e, collection){
          collection.remove({ agency_key: agency_key }, cb);
        });
      }, function(e){
          cb(e, 'remove');
      });
    }


    function importFiles(cb) {
      //Loop through each file and add agency_key
      async.forEachSeries(GTFSFiles, function(GTFSFile, cb){
        if(GTFSFile){
          var filepath = path.join(downloadDir, GTFSFile.fileNameBase + '.txt');
          if (!fs.existsSync(filepath)) return cb();
          console.log(agency_key + ': ' + GTFSFile.fileNameBase + ' Importing data');
          db.collection(GTFSFile.collection, function(e, collection){
            csv()
              .from.path(filepath, {columns: true})
              .on('record', function(line, index){
                 //remove null values
                for(var key in line){
                  if(line[key] === null){
                    delete line[key];
                  }
                }
                
                //add agency_key
                line.agency_key = agency_key;

                //convert fields that should be int
                if(line.stop_sequence){
                  line.stop_sequence = parseInt(line.stop_sequence, 10);
                }
                if(line.direction_id){
                  line.direction_id = parseInt(line.direction_id, 10);
                }

                //make lat/lon array
                if(line.stop_lat && line.stop_lon){
                  line.loc = [parseFloat(line.stop_lon), parseFloat(line.stop_lat)];
                  
                  //Calulate agency bounds
                  if(agency_bounds.sw[0] > line.loc[0] || !agency_bounds.sw[0]){
                    agency_bounds.sw[0] = line.loc[0];
                  }
                  if(agency_bounds.ne[0] < line.loc[0] || !agency_bounds.ne[0]){
                    agency_bounds.ne[0] = line.loc[0];
                  }
                  if(agency_bounds.sw[1] > line.loc[1] || !agency_bounds.sw[1]){
                    agency_bounds.sw[1] = line.loc[1];
                  }
                  if(agency_bounds.ne[1] < line.loc[1] || !agency_bounds.ne[1]){
                    agency_bounds.ne[1] = line.loc[1];
                  }
                }

                //insert into db
                collection.insert(line, function(e, inserted) {
                  if(e) { handleError(e); }
                });
              })
              .on('end', function(count){
                cb();
              })
              .on('error', handleError);
          });
        }
      }, function(e){
        cb(e, 'import');
      });
    }


    function postProcess(cb) {
      console.log(agency_key + ':  Post Processing data');

      async.series([
          agencyCenter
        , longestTrip
        , updatedDate
      ], function(e, results){
        cb();
      });
    }


    function agencyCenter(cb) {
      var agency_center = [
          (agency_bounds.ne[0] - agency_bounds.sw[0])/2 + agency_bounds.sw[0]
        , (agency_bounds.ne[1] - agency_bounds.sw[1])/2 + agency_bounds.sw[1]
      ];

      db.collection('agencies')
        .update({agency_key: agency_key}, {$set: {agency_bounds: agency_bounds, agency_center: agency_center}}, cb);
    }


    function longestTrip(cb) {
      /*db.trips.find({agency_key: agency_key}).for.toArray(function(e, trips){
          async.forEach(trips, function(trip, cb){
            db.collection('stoptimes', function(e, collection){

            });
            console.log(trip);
            cb();
          }, cb);
        });
      });*/
      cb();
    }

    function updatedDate(cb) {
      db.collection('agencies')
        .update({agency_key: agency_key}, {$set: {date_last_updated: Date.now()}}, cb);
    }
  }
});
Example #11
0
var express = require('express');
var app = express();

var mongo = require('mongodb'), format = require('util').format, ObjectID = require('mongodb').ObjectID;
var db = new mongo.Db('stonedb', new mongo.Server('localhost', 27017, {}), {safe: true});

db.open(function() {
 console.log("mongodb connection established");
});

/**
 * Get a list of message metadata within a certain radius from the user (based on provided lat/lon).
 */
app.get('/stoneapi/message/get/:lat/:lon/:radius', function(req, res) {

    db.collection('coll', function(err, collection) {
      if (err) throw err;

      //For the local messages, we just want to project out the following:
      // message _id, rating, latitude, longitude

      //Need to find upper and lower latitude/longitude bounds, go out about one second
      //in each direction... See http://en.wikipedia.org/wiki/Great-circle_distance
      var latTolerance = 0.0003 * req.params.radius / 100.0 * Math.abs(Math.cos(parseFloat(req.params.lon) * (180/Math.PI))); //Normalize latitude distance to about 100 feet
      var lonTolerance = 0.0003 * req.params.radius / 100.0;
      console.log("Selecting from (" + req.params.lat + "," + req.params.lon + ") with tolerance lat: " + latTolerance + " , lon: " + lonTolerance);

      collection.find({ lat: {$gt: (parseFloat(req.params.lat) - latTolerance), $lt: (parseFloat(req.params.lat) + latTolerance)},
                       lon: {$gt: (parseFloat(req.params.lon) - lonTolerance), $lt: (parseFloat(req.params.lon) + lonTolerance)}},
                      {_id:1, message:1, rating:1, lat:1, lon:1, username: 1, recipient: 1, private: 1}, function(err, cursor) {
                        if (err) throw err;
Example #12
0
 count: function(callback) {
     db.collection("urls", function(err, collection) {
         collection.count(function(err, count) { callback(count) });
     });
 },
Example #13
0
db.open(function(err, p_client) {
  db.authenticate(mongoUsername, mongoPassword, function(err) {
   //Change error handler when going into production 
   if (err) console.log(err);    
  });
});
Example #14
0
// web.js
var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');
var app = express();

app.use(logfmt.requestLogger());

app.get('/', function(req, res) {
  res.send('Hello World!');
});


var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/mydb';

mongo.Db.connect(mongoUri, function (err, db) {
	db.collection('mydocs', function(er, collection) {
		collection.insert({'anotherRecord': 'anotherRecordvalue'}, {safe: true}, function(er,rs) {});
	});
});



var port = Number(process.env.PORT || 5000);

app.listen(port, function() {
	console.log("Listening on " + port);
});
Example #15
0
var http = require("http");
var mongo = require("mongodb");

// Database config
var firstCol = "col_one";
var reduceCol = "col_two";

// Mongo server
var server = mongo.Server("127.0.0.1", 27017);
var db = new mongo.Db("test", server, { safe: true });

// Open database
db.open(function(err, db) {
    if (err) {
        process.exit(1);
    }
});

// Create server
var srv = http.createServer(function(req, res){
    // Write the content of col_one
    res.write("ITEMS FROM test DB, collection: " + firstCol + "\n");
    
    // Print items from col_one
    printItems(firstCol, res, function(err, collection) {
        if (err) { return res.end("Something went wrong.:("); }
        
        // Start reduce function
        var mapFunction1 = function() {
            emit(this.cust_id, this.price);
        };
Example #16
0
Post.remove = function(name, day, title, callback) {
  //打开数据库
  mongodb.connect(settings.url, function (err, db) {
    if (err) {
      return callback(err);
    }
    //读取 posts 集合
    db.collection('posts', function (err, collection) {
      if (err) {
        db.close();
        return callback(err);
      }
      //查询要删除的文档
      collection.findOne({
        "name": name,
        "time.day": day,
        "title": title
      }, function (err, doc) {
        if (err) {
          db.close();
          return callback(err);
        }
        //如果有 reprint_from,即该文章是转载来的,先保存下来 reprint_from
        var reprint_from = "";
        if (doc.reprint_info.reprint_from) {
          reprint_from = doc.reprint_info.reprint_from;
        }
        if (reprint_from != "") {
          //更新原文章所在文档的 reprint_to
          collection.update({
            "name": reprint_from.name,
            "time.day": reprint_from.day,
            "title": reprint_from.title
          }, {
            $pull: {
              "reprint_info.reprint_to": {
                "name": name,
                "day": day,
                "title": title
            }}
          }, function (err) {
            if (err) {
              db.close();
              return callback(err);
            }
          });
        }

        //删除转载来的文章所在的文档
        collection.remove({
          "name": name,
          "time.day": day,
          "title": title
        }, {
          w: 1
        }, function (err) {
          db.close();
          if (err) {
            return callback(err);
          }
          callback(null);
        });
      });
    });
  });
};
Example #17
0
// Initialization
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// See https://stackoverflow.com/questions/5710358/how-to-get-post-query-in-express-node-js
app.use(bodyParser.json());
// See https://stackoverflow.com/questions/25471856/express-throws-error-as-body-parser-deprecated-undefined-extended
app.use(bodyParser.urlencoded({ extended: true }));

// Mongo initialization
var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/test';
var mongo = require('mongodb');
var db = mongo.Db.connect(mongoUri, function(error, databaseConnection)
{
	db = databaseConnection;
});
// Cross domain
app.all('*', function(req, res, next) 
{
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Origin", 'PUT, GET, POST');
	res.header("Access-Control-Allow-Origin", "X_Requested-With");
	next();
});


app.get('/', function(request, response) 
{
	response.set('Content-Type', 'text/html');
	var indexPage = '';
	db.collection('locations', function(er, collection) 
Example #18
0
Post.reprint = function(reprint_from, reprint_to, callback) {
  mongodb.connect(settings.url, function (err, db) {
    if (err) {
      return callback(err);
    }
    db.collection('posts', function (err, collection) {
      if (err) {
        db.close();
        return callback(err);
      }
      //找到被转载的文章的原文档
      collection.findOne({
        "name": reprint_from.name,
        "time.day": reprint_from.day,
        "title": reprint_from.title
      }, function (err, doc) {
        if (err) {
          db.close();
          return callback(err);
        }

        var date = new Date();
        var time = {
            date: date,
            year : date.getFullYear(),
            month : date.getFullYear() + "-" + (date.getMonth() + 1),
            day : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
            minute : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + 
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
        }

        delete doc._id;//注意要删掉原来的 _id

        doc.name = reprint_to.name;
        doc.head = reprint_to.head;
        doc.time = time;
        doc.title = (doc.title.search(/[转载]/) > -1) ? doc.title : "[转载]" + doc.title;
        doc.comments = [];
        doc.reprint_info = {"reprint_from": reprint_from};
        doc.pv = 0;

        //更新被转载的原文档的 reprint_info 内的 reprint_to
        collection.update({
          "name": reprint_from.name,
          "time.day": reprint_from.day,
          "title": reprint_from.title
        }, {
          $push: {
            "reprint_info.reprint_to": {
              "name": doc.name,
              "day": time.day,
              "title": doc.title
          }}
        }, function (err) {
          if (err) {
            db.close();
            return callback(err);
          }
        });

        //将转载生成的副本修改后存入数据库,并返回存储后的文档
        collection.insert(doc, {
          safe: true
        }, function (err, post) {
          db.close();
          if (err) {
            return callback(err);
          }
          callback(err, post[0]);
        });
      });
    });
  });
};
Example #19
0
function connect( cb ) {
  if ( db ) return cb(null, db);
  connection.open(function(err, db_) {
    return cb(err, db = db_);
  })
}
Example #20
0
var scheduler = function (options) {

    var mongo = require('mongodb')
        , redis = require('redis')
        , async = require('async')
        , userBee = require('./user-bee')(options);

    var mongoServer = new mongo.Server(options.mongodb.host, options.mongodb.port, options.mongodb.options);
    var db = new mongo.Db('user_bee', mongoServer, {safe:false});
    var laterRefs = new Array();

    var redis = redis.createClient(options.redis.port, options.redis.host);
    if (options.redis.hasOwnProperty('password')) {
        redis.auth(options.redis.password);
    }

    /**
     * Private functions
     */

    var _processTrigger = function (trigger) {
        db.collection('attributes', function (err, collection) {
            if (err) {
                console.error("Could not fetch attributes collection from mongodb: " + err);
                return false;
            }

            //TODO: Exclude unsubscribed users
            //Fetch users for whom this trigger has not been triggered yet
            var queryCondition = ('query' in trigger) ? trigger.query : ('queryFunction' in trigger ? eval('(' + trigger.queryFunction + ')()') : {})
            var query = {
                '$and': [
                    {
                        'triggersTriggered': {'$ne': trigger._id}
                    },
                    queryCondition
                ]
            };

            collection.find(query).each(function (err, userAttributes) {
                if (err) {
                    console.error("Could not query attributes collection from mongodb: " + err);
                    return false;
                }
                if (userAttributes == null) {
                    return true;
                }

                userBee.trigger(trigger, userAttributes, function (err) {
                    if (err) {
                        console.error("Error triggering trigger: " + err);
                        return false;
                    }

                    //Mark trigger as triggered in DB

                    db.collection('attributes', function (err, updateCollection) {
                        if (err) {
                            console.error("Could not fetch attributes collection from mongodb: " + err);
                            return false;
                        }

                        var query = {
                            userId: userAttributes.userId
                        };

                        var pushCmd = {
                            '$push': {
                                'triggersTriggered': trigger._id
                            }
                        };

                        updateCollection.update(query, pushCmd, {safe: true, upsert: true}, function (err, result) {
                            if (err) {
                                console.error("Could not mark trigger as triggered in mongodb: " + err);
                                return false;
                            }
                            return true;
                        });
                    });

                });
            });
        });
    };

    var _startScheduler = function () {
        console.log("Starting scheduler");
        db.open(function (err, db) {
            if (err) {
                console.error("Could not connect to mongodb: " + err);
                return false;
            }
            db.collection('triggers', function (err, collection) {
                if (err) {
                    console.error('Could not load triggers from mongodb: ' + err)
                    return false;
                }
                var cron = require('later').cronParser
                    , later = require('later').later;
                collection.find().toArray(function (err, docs) {
                    if (err) {
                        console.error('Could not load triggers from mongodb: ' + err)
                        return false;
                    }
                    async.each(docs,
                        function (trigger, callback) {
                            var laterRef = later(1);
                            laterRef.exec(cron().parse(trigger.frequency, true), (new Date()), _processTrigger, trigger);
                            laterRefs.push(laterRef);
                            callback();
                        },
                        function (err) {
                            if (err) {
                                console.error('Error processing trigger: ' + err)
                                return false;
                            }
                        }
                    );
                });
            });
        });
    };

    var _stopScheduler = function () {
        console.log("Stopping scheduler");
        for (var i in laterRefs) {
            laterRefs[i].stopExec();
        }
        laterRefs = new Array();
        db.close();
    };

    return {
        addTrigger: function (trigger, callback) {
            db.open(function (err, db) {
                if (err) {
                    console.error("Could not connect to mongodb: " + err);
                    return false;
                }

                db.collection('triggers', function (err, collection) {
                    if (err) {
                        return callback(err);
                    }
                    var doc = {
                        frequency: trigger.frequency,
                        email: trigger.email,
                        createdAt: Math.round((new Date()).getTime() / 1000)
                    };
                    if ('query' in trigger) {
                        doc.query = trigger.query;
                    }
                    if ('queryFunction' in trigger) {
                        doc.queryFunction = trigger.queryFunction.toString();
                    }
                    collection.insert(doc, {safe: true}, function (err, result) {
                        if (err) {
                            return callback(err);
                        }
                        //Publish that a new trigger was added
                        redis.publish("addTrigger", JSON.stringify(trigger), function (err, result) {
                            callback(result);
                        });
                    });
                });
            });
        },
        start: function () {
            redis.on("message", function (channel, message) {
                console.log("New trigger added, restarting scheduler");
                _stopScheduler();
                _startScheduler();
            });
            redis.subscribe("addTrigger");
            _startScheduler();
        }
    }

};
Example #21
0
#!/usr/bin/env node
/**
 * dump_logs.js
 * Dumps the log database in log file format.
 */
var mongodb = require('mongodb'),
    server = new mongodb.Server('127.0.0.1', '27017', {}),
    connection = new mongodb.Db('bioasq-at', server, { safe: false }),
    querystring = require('querystring');

connection.open(function (err, conn) {
    if (err) {
        process.stdout.write('Could not open connection.');
        process.exit(-1);
    }

    conn.collection('log', function (err, log) {
        if (err) {
            process.stdout.write('Could not open `logs` collection.');
            process.exit(-1);
        }
        /*
         * TODO: Modify here to change the query
         */
        var cursor = log.find(
            { path: 'login' },  // db query: set key and value of the fields to match
            { time: false, _id: false } // set fields to not return to false
        );

        cursor.count(function (err, count) {
            console.log(count + ' log entries found.');
Example #22
0
    var _processTrigger = function (trigger) {
        db.collection('attributes', function (err, collection) {
            if (err) {
                console.error("Could not fetch attributes collection from mongodb: " + err);
                return false;
            }

            //TODO: Exclude unsubscribed users
            //Fetch users for whom this trigger has not been triggered yet
            var queryCondition = ('query' in trigger) ? trigger.query : ('queryFunction' in trigger ? eval('(' + trigger.queryFunction + ')()') : {})
            var query = {
                '$and': [
                    {
                        'triggersTriggered': {'$ne': trigger._id}
                    },
                    queryCondition
                ]
            };

            collection.find(query).each(function (err, userAttributes) {
                if (err) {
                    console.error("Could not query attributes collection from mongodb: " + err);
                    return false;
                }
                if (userAttributes == null) {
                    return true;
                }

                userBee.trigger(trigger, userAttributes, function (err) {
                    if (err) {
                        console.error("Error triggering trigger: " + err);
                        return false;
                    }

                    //Mark trigger as triggered in DB

                    db.collection('attributes', function (err, updateCollection) {
                        if (err) {
                            console.error("Could not fetch attributes collection from mongodb: " + err);
                            return false;
                        }

                        var query = {
                            userId: userAttributes.userId
                        };

                        var pushCmd = {
                            '$push': {
                                'triggersTriggered': trigger._id
                            }
                        };

                        updateCollection.update(query, pushCmd, {safe: true, upsert: true}, function (err, result) {
                            if (err) {
                                console.error("Could not mark trigger as triggered in mongodb: " + err);
                                return false;
                            }
                            return true;
                        });
                    });

                });
            });
        });
    };
Example #23
0
var express = require("express");
var url = require("url");
var mongodb = require('mongodb');
var swagger = require("../../Common/node/swagger.js");
var connect = require("connect");

var dbName = 'swagger-user';
var dbHost = '127.0.0.1';
var dbPort = 27017;

var dbServer = new mongodb.Server(dbHost, dbPort, {});
var db = new mongodb.Db(dbName, dbServer);

db.open(function(err, db) {
  if (err || !db) {
    console.log('Cannot connect to database');
  } else {
    // Start Expressjs handler
    var app = express.createServer(
      connect.bodyParser(), /* Express' bodyParser() is not working propper? */
      function(req, res, next) {
        if (req.db === undefined) {
          req.db = db; }
        next(); });
    app.use(express.logger('dev'));
    
    // Set swagger actions 
    swagger.setAppHandler(app);
    swagger.discoverFile(__dirname + "/res.User.js");
    
    // Add validation
Example #24
0
                userBee.trigger(trigger, userAttributes, function (err) {
                    if (err) {
                        console.error("Error triggering trigger: " + err);
                        return false;
                    }

                    //Mark trigger as triggered in DB

                    db.collection('attributes', function (err, updateCollection) {
                        if (err) {
                            console.error("Could not fetch attributes collection from mongodb: " + err);
                            return false;
                        }

                        var query = {
                            userId: userAttributes.userId
                        };

                        var pushCmd = {
                            '$push': {
                                'triggersTriggered': trigger._id
                            }
                        };

                        updateCollection.update(query, pushCmd, {safe: true, upsert: true}, function (err, result) {
                            if (err) {
                                console.error("Could not mark trigger as triggered in mongodb: " + err);
                                return false;
                            }
                            return true;
                        });
                    });

                });
Example #25
0

var crypto 		= require('crypto')
var MongoDB 	= require('mongodb').Db;
var Server 		= require('mongodb').Server;
var moment 		= require('moment');

var fmsConfig = require('../config')

var dbPort 		= fmsConfig.mongodb.port;
var dbHost 		= fmsConfig.mongodb.host;
var dbName 		= fmsConfig.mongodb.db;

/* establish the database connection */

var db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1});
	db.open(function(e, d){
	if (e) {
		console.log(e);
	}	else{
		console.log('connected to database :: ' + dbName);
	}
});
// var db = global.fmsDb;

var accounts = db.collection('VD_Taxi1');


/* record insertion, update & deletion methods */

exports.addNewData = function(newData, callback)
Example #26
0
var mongodb = require('mongodb')
var products = require('./product/build_inventory')
var categories = require('./category/build_categorydata')

var db = new mongodb.Db('tikvah', new mongodb.Server('localhost', 27017, {auto_reconnect:true}), {safe:true});

db.open(function (error, client) {
    categories.execute(db,client)
    products.execute(db,client)
    
})


Example #27
0
 coll.insert(doc, function (err, coll) {
   if (err) console.log(err);
   db.close();
   res.send('', 201);
 });
Example #28
0
require.paths.unshift('../lib');
require.paths.unshift('../external-libs/bson');

var Db = require('mongodb').Db,
  Server = require('mongodb').Server,
  Cursor = require('mongodb').Cursor,
  Collection = require('mongodb').Collection,
  sys = require('sys');  
var BSON = require('bson');

var db = new Db('streaming_benchmark', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {})
// Set native deserializer
db.bson_deserializer = BSON;
db.bson_serializer = BSON;
db.pkFactory = BSON.ObjectID;

// Open the db
db.open(function(err, client) {
  client.collection('streaming_benchmark', function(err, collection) {
    collection.remove({}, function(err, result) {
      // Benchmark
      var started_at = new Date().getTime(); 
      // Add documents
      for(var i = 0; i < 100000; i++) {
      // for(var i = 0; i < 1000; i++) {
        collection.save({'i':i, 'a':i, 'c':i, 'd':{'i':i}}, function(err, result){});
      }    
      sys.puts("save recs: " + ((new Date().getTime() - started_at)/1000) + "seconds"); 

      // Benchmark
      var started_at = new Date().getTime(); 
Example #29
0
var mongodb = require('mongodb')
, server = new mongodb.Server('localhost', 27017 )
, Db = new mongodb.Db('filesite', server, {w: -1});

Db.open(function(err) {
  if (err) throw err;

  console.log("Connected to database!");
});

module.exports = Db;
Example #30
0
    app.get(urlPrefix + '/:db/:collection/:id?', function(req, res) { 
        var query = req.query.query ? JSON.parse(req.query.query) : {};

        // Providing an id overwrites giving a query in the URL
        if (req.params.id) {
            query = {'_id': new BSON.ObjectID(req.params.id)};
        }
        var options = req.params.options || {};

        var test = ['limit','sort','fields','skip','hint','explain','snapshot','timeout'];

        for( o in req.query ) {
            if( test.indexOf(o) >= 0 ) {
                options[o] = req.query[o];
            } 
        }

        var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, serverParams), dbParams);
        db.open(function(err,db) {
            if (err) {
                logger.error('Db open error: ' + err.message);
                res.status(500).send(err.message);
                return;
            }

            db.authenticate(config.db.username, config.db.password, function () {
                db.collection(req.params.collection, function(err, collection) {
                    if (err) {
                        db.close();
                        logger.error('Error getting collection ' + collection + ': ' + err.message);
                        res.status(500).send(err.message);
                        return;
                    }

                    collection.find(query, options, function(err, cursor) {
                        if (err) {
                            db.close();
                            logger.error('Error finding document(s): ' + err.message);
                            res.status(500).send(err.message);
                            return;
                        }

                        cursor.toArray(function(err, docs){
                            if (err) {
                                db.close();
                                logger.error('Error getting database cursor as array: ' + err.message);
                                res.status(500).send(err.message);
                                return;
                            } 

                            var result = [];          
                            if(req.params.id) {
                                if(docs.length > 0) {
                                    result = docs[0];
                                    res.json(result);
                                } else {
                                    res.status(404).json({ ok: 0 });
                                }
                            } else {
                                docs.forEach(function(doc) {
                                    result.push(doc);
                                });

                                var outputType = req.query.output || collectionOutputType;
                                result = transformCollection(outputType, result)
                                res[outputType](result);
                            }
                        
                            db.close();
                        });
                    });
                });
            });
        });
    });