Example #1
0
Item.prototype.removeOffer = function(itemId){
  var id = Mongo.ObjectID(itemId);
  _.remove(this.offers, function(item){
    return item === id;
  });
};
 foundUser.on('data', function (user) {
   // var id = user._id.toString();
   /*TODO : check if already attending, and if true NO OP */
   DB.collection('corgievent').update({_id: ObjectID(eventID)}, { $addToSet: {attendeeIDs: {username: user.name} } });
   res.end();
 });
Example #3
0
Message.read = function(id, cb){
  var _id = Mongo.ObjectID(id);
  Message.collection.findAndModify({_id:_id}, [], {$set:{isRead:true}}, function(err, msg){
    iterator(msg, cb);
  });
};
Example #4
0
function getFightStatistics(userId) {
	return Fight.aggregate(
		[{$match: {$or: [{opponent: ObjectId(userId)}, {challenger: ObjectId(userId)}]}},
			{
				$project: {
					winningUser: '******',
					losingUser: {
						$cond: [
							{$ne: ['$winningUser', null]},
							{$cond: [{$ne: ['$winningUser', '$challenger']}, '$challenger', '$opponent']},
							null
						]
					},
					opponentUser: '******',
					challengerUser: '******'
				}
			}
		]).exec().then(function (fightData) {

			var fightResults = {};
			var victims = {};
			var userIds = [];
			if (fightData) {
				var userStats = {};
				userStats.wins = 0;
				userStats.losses = 0;
				userStats.ties = 0;
				userStats.totalGames = 0;

				var fightIds = [];

				_.forEach(fightData, function (fightDataElement) {

					fightIds.push(fightDataElement._id);
					if (fightDataElement.winningUser) {
						if (fightDataElement.winningUser == userId) {
							userStats.wins++;

							if (fightDataElement.opponentUser == userId) {
								if (!victims[fightDataElement.challengerUser]) {
									victims[fightDataElement.challengerUser] = {};
									victims[fightDataElement.challengerUser].beatings = 0;
									victims[fightDataElement.challengerUser]._id = fightDataElement.challengerUser;
								}

								victims[fightDataElement.challengerUser].beatings++;
								userIds.push(fightDataElement.challengerUser);
							}
							else {
								if (!victims[fightDataElement.opponentUser]) {
									victims[fightDataElement.opponentUser] = {};
									victims[fightDataElement.opponentUser].beatings = 0;
									victims[fightDataElement.opponentUser]._id = fightDataElement.opponentUser;
								}

								victims[fightDataElement.opponentUser].beatings++;
								userIds.push(fightDataElement.opponentUser);
							}
						}
						else {
							userStats.losses++;
						}

						userStats.totalGames++;
					}
					else {
						userStats.ties++;
						userStats.totalGames++;
					}

					userStats.winPercentage = userStats.wins > 0 ?
						Math.round(((userStats.wins + (userStats.ties * 0.5)) / userStats.totalGames) * 100) : 0;
				});

				fightResults.fightWinPercentage = userStats.winPercentage + '% (' + userStats.wins + '-' + userStats.losses + '-' + userStats.ties + ')';
				fightResults.topVictims = _.take(_.sortByOrder(victims, ['beatings'], [false]), 5);

				userIds = _.unique(userIds);

				return User.find({"_id": {$in: userIds}}).then(function (users) {

					_.forEach(fightResults.topVictims, function (victim) {
						var userIndex = _.findIndex(users, function (user) {
							return user._id == victim._id;
						});

						victim.userNick = users[userIndex].nick;
					});

					return FightRound.find({fight: {$in: fightIds}}).then(function (fightRounds) {
						var fightRoundStats = {};
						fightRoundStats.wins = 0;
						fightRoundStats.losses = 0;
						fightRoundStats.ties = 0;
						fightRoundStats.totalRounds = 0;

						_.forEach(fightRounds, function (fightRound) {
							if (fightRound.winningUser) {
								if (fightRound.winningUser == userId) {
									fightRoundStats.wins++;
								}
								else {
									fightRoundStats.losses++;
								}
							}
							else {
								fightRoundStats.ties++;
							}

							fightRoundStats.totalRounds++;

							fightRoundStats.winPercentage = fightRoundStats.wins > 0 ?
								Math.round(((fightRoundStats.wins + (fightRoundStats.ties * 0.5)) / fightRoundStats.totalRounds) * 100) : 0;
						});

						fightResults.fightRoundWinPercentage = fightRoundStats.winPercentage + '% (' + fightRoundStats.wins + '-' + fightRoundStats.losses + '-' + fightRoundStats.ties + ')';

						return fightResults;
					});
				});
			}

			fightResults.fightWinPercentage = '0% (0-0-0)';
			fightResults.victims = null;
			fightResults.fightRoundWinPercentage = '0% (0-0-0)';

			return fightResults;
		});
}
Example #5
0
var moment          = require('moment');
var util            = require('./lib/util.js');
var handleLink      = require('./lib/handleLink.js'); 
var setupReminders  = require('./lib/setupReminders.js');
var initCheck       = 0;
var preloaded       = []; /* Holds commands, database, twitter in that order */
var config          = require('./config.js');
var checkNotes      = require('./cmd/fetch/notes.js');
var Twit            = require('twit');
var twit            = new Twit(config.twitter);
var twitStream      = twit.stream('user', { 'with': 'user' });
var ObjectID        = require('mongodb').ObjectID;
var botNameID       = ObjectID('53597eda1ba435599e000016');

require('./lib/loadCommands.js')(init);
require('./lib/db.js')(init);

function init(loadedObj) {

    preloaded.push(loadedObj);

    if (preloaded.length === 2) {
        initIRC();
    }

}

function initIRC()  {

    var btcexchange = config.standardbtcexchange;
    var uptime      = moment();
Example #6
0
app.get("/api/users/:_id", function(req, res) {
  users.findOne({_id: mongodb.ObjectID(req.params._id)}, function(err, item) {
    res.send(item);
  });
});
Example #7
0
			db.collection('users').findOne({"username":username,"app":app._id}, function(err, userExtracted){
				if(userExtracted!=null){

				    var messageToHash = 'updatePosition|'+agentid+'|'+latitude+'|'+longitude+'|'+timestamp;
				    
				    var hashCalculated = crypto.createHmac('md5', userExtracted.token).update(messageToHash).digest('hex');
					
				    if(debugEnabled){
					    console.log(" * message: ["+messageToHash+"]");
					    console.log(" * hash submitted: ["+hashSubmitted+"]");
					    console.log(" * hash calculated: ["+hashCalculated+"]");
				    }
				    
				    if(hashSubmitted===hashCalculated){
				    	
				    	db.collection('agents').findOne({ _id: mongodb.ObjectID(agentid), user: userExtracted._id }, function(err, agentFound){
				    		if(agentFound==null){
				    			self.emit('error',"cannot find agent "+agentid+", username: "******"error: %j",err);
						   							self.emit('error',"error: "+error.message, responseHash, response, bayeux);
						    				   }else{

						    					   //calc the distance
						    					   var distanceTraveled = distance.getDistance({'latitude':agentFound.loc[1], 'longitude':agentFound.loc[0] }, {'latitude':latitude, 'longitude':longitude });
						    					   //calc the speed
						    					   var prevDate = agentFound.date;
						    					   var kmh = "";
						    					   if(prevDate!=null){
						    						   var diffTime = (new Date().getTime() - prevDate.getTime())/1000;
						    						   kmh = distanceTraveled * 3600 / diffTime;
						    					   }
						    					   
						    					   self.emit( 'update-position-response',appalias,agentid,latitude,longitude, distanceTraveled, kmh, responseHash, response, bayeux);
						    					   
						    					   try{
						    						   var history = {
						    								   'agent': mongodb.ObjectID(agentid),
						    								   'loc': [parseFloat(longitude), parseFloat(latitude)],
						    								   'date': new Date()
						    						   };
						    						   db.collection('history').insert(history);
						    						   
						    						   if(debugEnabled)
						    							   console.log(" * inserting history: %j ",history);
						    						   
						    					   }catch (e) {
						    						   console.log(" * exception inserting history: "+e);
						    					   }
						    					   
						    				   }
						    			});
				    		}
				    	});
				    	

				    	
				    	
				    }else{
						self.emit('error',"hash not matching", responseHash, response, bayeux);
				    }
				    
										
				}else{
					self.emit('error',"cannot find user: "+username, responseHash, response, bayeux);
				}
			});
Example #8
0
Recipe.remove = function(query, cb){
  var id = Mongo.ObjectID(query);
  Recipe.collection.remove({_id: id}, cb);

};
Example #9
0
Plot.findById = function(id, cb){
  var _id = Mongo.ObjectID(id);
  Plot.collection.findOne({_id:_id}, cb);
};
Example #10
0
 static findByDishId(dishId, fn) {
     dishId = Mongo.ObjectID(dishId);
     dishes.findOne({_id:dishId}, (e,d)=>{
         fn(d);
     });
 }
Example #11
0
exports.query = function(req, res) {
    db.collection('groups').findOne({ '_id':ObjectId(req.params.id) },
    function(err, group) {
        res.json(group);
    });
};
Example #12
0
const hooks = require('hooks');
const {MongoClient} = require('mongodb');
const ObjectID = require('mongodb').ObjectID;

let db;

const address = [
    {"_id":ObjectID("579f21ae98684924944651bd"),"_class":"works.weave.socks.users.entities.Address","number":"69","street":"Wilson Street","city":"Hartlepool","postcode":"TS26 8JU","country":"United Kingdom"},
    {"_id":ObjectID("579f21ae98684924944651c0"),"_class":"works.weave.socks.users.entities.Address","number":"122","street":"Radstone WayNet","city":"Northampton","postcode":"NN2 8NT","country":"United Kingdom"},
    {"_id":ObjectID("579f21ae98684924944651c3"),"_class":"works.weave.socks.users.entities.Address","number":"3","street":"Radstone Way","city":"Northampton","postcode":"NN2 8NT","country":"United Kingdom"}
];


const card = [
    {"_id":ObjectID("579f21ae98684924944651be"),"_class":"works.weave.socks.users.entities.Card","longNum":"8575776807334952","expires":"08/19","ccv":"014"},
    {"_id":ObjectID("579f21ae98684924944651c1"),"_class":"works.weave.socks.users.entities.Card","longNum":"8918468841895184","expires":"08/19","ccv":"597"},
    {"_id":ObjectID("579f21ae98684924944651c4"),"_class":"works.weave.socks.users.entities.Card","longNum":"6426429851404909","expires":"08/19","ccv":"381"}
];

const cart = [
    {"_id":ObjectID("579f21de98689ebf2bf1cd2f"),"_class":"works.weave.socks.cart.entities.Cart","customerId":"579f21ae98684924944651bf","items":[{"$ref":"item","$id":ObjectID("579f227698689ebf2bf1cd31")},{"$ref":"item","$id":ObjectID("579f22ac98689ebf2bf1cd32")}]},
    {"_id":ObjectID("579f21e298689ebf2bf1cd30"),"_class":"works.weave.socks.cart.entities.Cart","customerId":"579f21ae98684924944651bfaa","items":[]}
];


const item = [
    {"_id":ObjectID("579f227698689ebf2bf1cd31"),"_class":"works.weave.socks.cart.entities.Item","itemId":"819e1fbf-8b7e-4f6d-811f-693534916a8b","quantity":20,"unitPrice":99.0}
];


const customer = [
Example #13
0
Item.prototype.addOffer = function(id){
  var offerId = Mongo.ObjectID(id);
  this.offers.push(offerId);
};
Example #14
0
Item.deleteAllByUserId = function(userId, fn){
  userId = Mongo.ObjectID(userId);
  items.remove({userId:userId}, function(err, count){
    fn(count);
  });
};
Example #15
0
 static plant(userId, fn){
   userId = Mongo.ObjectID(userId);
   var tree = new Tree(userId);
   trees.save(tree, ()=>fn(tree));
 }
Example #16
0
Plot.remove = function(id, cb){
  console.log(id);
  id = Mongo.ObjectID(id);
  Plot.collection.remove({_id:id}, cb);
};
Example #17
0
app.delete("/api/users?id=*", function(req, res) {
    users.remove({ ID: mongodb.ObjectID(req.params._id) }, () => {
        res.send("delete");
    });
});
Example #18
0
Plot.getItinPlots = function(o, cb){
  console.log(o.pageId);
  var id = Mongo.ObjectID(o.pageId);
  console.log(id);
  Plot.collection.find({pageId:id}).sort({date: 1, time: 1}).toArray(cb);
};
Example #19
0
app.delete("/api/users/:_id", function(req, res) {
  users.remove({_id: mongodb.ObjectID(req.params._id)}, function() {
    res.send("delete");
  });
});
Example #20
0
Question.findById = function(id, cb){
  id = (typeof id === 'string') ? Mongo.ObjectID(id) : id;
  Question.collection.findOne({_id:id}, function(err, qstn){
     cb(err, linktoProto(qstn));
  });
};
Example #21
0
exports.findById = function (id, cb) {
    db.get().collection('artists').findOne({_id: ObjectID(id)}, function (err, doc) {
        cb(err, doc);
    })
};
Example #22
0
Question.deleteById = function(id, cb){
  id = (typeof id === 'string') ? Mongo.ObjectID(id) : id;
  Question.collection.findAndRemove({_id : id}, cb);
};
Example #23
0
Database.prototype.ObjectId = function(string) {
  return (string) ? ObjectId(string) : new ObjectId().toString();
};
Example #24
0
 it('should create a new Goal object', function(done){
   var reqBody = {name:'Be a Plumber', due:'2015-02-02', tags:'job, career', userId: Mongo.ObjectID('000000000000000000000001')};
   Goal.create(reqBody, function(err, g){
     expect(g).to.be.instanceof(Goal);
     expect(g.userId).to.be.instanceof(Mongo.ObjectID);
     expect(g._id).to.be.instanceof(Mongo.ObjectID);
     expect(g.name).to.equal('Be a Plumber');
     expect(g.due).to.be.instanceof(Date);
     expect(g.tags).to.have.length(2);
     expect(g.tasks).to.have.length(0);
     done();
   });
 });
Example #25
0
 collection.update({_id: ObjectId(req.params.id)}, req.body, function (err, result) {
     collection.findOne({_id: ObjectId(req.params.id)}, function (e, result) {
         if (e) return next(e)
         res.send(result)
     })
 });
Example #26
0
 static deleteByDrawingId(drawingId, fn) {
   drawingId = Mongo.ObjectID(drawingId);
   drawingCollection.remove({_id:drawingId}, (e, drawing)=>{
     fn(drawing);
   });
 }
Example #27
0
User.deleteById = function(id, fn){
  var _id = Mongo.ObjectID(id);
  users.remove({_id:_id}, function(err, count){
    fn(count);
  });
};
Example #28
0
exports.destroy = (req, res)=>{
  var _id = Mongo.ObjectID(req.params.id);

  tasks.findAndRemove({_id:_id}, ()=>res.redirect('/tasks'));
};
Example #29
0
File: user.js Project: badave/clola
User.addToSetById = function(user_id, updateObject, callback) {
  var query = user_id ? {"_id": ObjectID(user_id)} : {};
  db.findAndModify("users", query, {}, {"$addToSet": updateObject}, {"new": true}, function(err, user) {
    return callback(err, user);
  });
};
Example #30
0
/**
  * Helper to set ObjectID type for `_id` queries.
  * Forces anything named `_id` to be the `ObjectID` type.
  */
function updateIdQuery (query) {
  if (query._id && query._id.length) {
    query._id = ObjectID(query._id);
  }
}