Example #1
0
 docs.map((old) => {
   var doc = {
     _id: old._id,
     replies: {
       permissions: old.responses.no_permission_response,
       welcome: old.responses.welcome_message,
       nsfw: old.responses.nsfw_disallowed_response,
       timeout: 'default'
     },
     settings: {
       welcoming: old.settings.welcoming,
       prefix: false
     }
   }
   newCust.insert(doc, function (err, doc) {
     if (err) {
       reject('Insertion failiure, ' + err)
     } else if (doc) {
       counter++
       if (counter >= count) {
         load.stop()
         Logger.info('Customization transfer complete, transferred ' + counter + ' documents.')
         count = 0
         counter = 0
         resolve()
       }
     }
   })
 })
Example #2
0
  "register": function(id, data){
		if(!Array.isArray(data)){
			var error = {error: "no username/pass array given"};
			helpers.log(error);
			helpers.emit(id, error)
			return;
		 }
		var userName = (data[0] || +new Date()).toString();
		var password = (data[1] || Math.random().toString(36).slice(2)).toString();
		var doc = {"userName": userName, "password": password};
		
		userNamesDB.insert(doc, function(err, newDoc){
			if(err){
				if(err.errorType === "uniqueViolated"){
					var error = {error: "username taken"};
					helpers.log(error);
					helpers.emit(id, error);
				}else{
					var error = {error: "database error 1"};
					helpers.log(error);
				}
			}else{
				// start streaming after register
				helpers.newStreamer(id, userName); 
				helpers.log(doc);
				helpers.emit(id, {"userName": userName, "password": password, "error": 0});
			}
		});
  },
Example #3
0
exports.save = function(id, data, callback) {
  if (id) {
    getById(id, function(err, result) {
      if (!result) {
        return callback(404);
      }
      if (result.user !== data.user) {
        // FIXME: 403 is not properly
        return callback(403);
      }

      data.updated_at = +new Date();
      bin.update({_id: id}, data, {upsert: true}, function() {
        callback && callback(null, data);
      });
    });
  }

  else {
    data.created_at = data.updated_at = +new Date();
    bin.insert(data, function(err, result) {
      callback && callback(null, result);
    });
  }
};
Example #4
0
		db.find ({totals: true},function(err, docums) {
			if (docums.length ===0) {
				db.insert({totals: true, userList: [profile.name]});
			} else{
				db.update({totals: true},{ $push: { userList: profile.name} },{},function(){});
			}
		});
 app.get("/new/:url*", function(req, res) {
  var url = req.params.url + req.params[0];
  var counter = syncCount();


  if (validator.isURL(url)) {

   var i = counter++;
   var shorty = req.protocol + '://' + req.host + '/' + i;
   var doc = {
    original_url: url,
    short_url: shorty,
    lid: i
   };

   db.insert(doc, function(err) { // Callback is optional
    // newDoc is the newly inserted document, including its _id
    if (err) return err;
    // newDoc has no key called notToBeSaved since its value was undefined
   });

   res.send({
    original_url: url,
    short_url: shorty
   });
  }
  else {
   res.send({
    "error": "URL invalid"
   });
  }
 });
Example #6
0
 return new Promise(function (resolve, reject) {
   var doc = {
     _id: guild.id,
     version: 3,
     superUser: guild.owner.id,
     blacklisted: false,
     perms: {
       level1: ['NaN'],
       level2: ['NaN'],
       level3: ['NaN'],
       negative: ['NaN'],
       nsfw: ['NaN'],
       roles: {
         level1: ['NaN'],
         level2: ['NaN'],
         level3: ['NaN'],
         negative: ['NaN']
       }
     }
   }
   database.insert(doc, function (err, doc) {
     if (err) {
       reject(err)
     } else if (doc) {
       resolve(doc)
     }
   })
 })
Example #7
0
photos_on_disk.forEach(function(photo){
    photos.insert({
        name: photo,
        likes: 0,
        dislikes: 0
    });
});
Example #8
0
                function ( pathScreenshot, done ) {
                    var subtitulo;
                    if ( job.data.options.subtitles ) {
                        subtitulo =  path.basename(job.data.options.subtitles);
                    } else {
                        subtitulo = '';
                    }

                    var imagen = {
                        path: job.data.output,
                        nombre: path.basename ( job.data.output ),
                        fecha: Date.now(),
                        desde: job.data.options.from,
                        hasta:  job.data.options.to,
                        texto: job.data.options.text,
                        colores: job.data.options.colors,
                        resize: job.data.options.resize,
                        video: inputVideo,
                        ip: job.data.ip,
                        screenshot: path.basename(pathFrame),
                        idVideo: video._id,
                        subtitulo: subtitulo,
                        options: job.data.options
                    };
                    db.insert( imagen, done );
                }
Example #9
0
		socket.on('handshake?', function(u) {
			name = u || 'anon';
			myTank = {
				name: name,
				tank: {
					x: 50,
					y: 50,
					dir: 0
				},
				bullets: [],
				stack: [],
				update: function() {
					db.update({
						_id: id
					}, {
						'tank.x': this.tank.x,
						'tank.y': this.tank.y,
						'tank.dir': this.tank.dir
					}, {}, function(err, thing) {
						socket.emit('updatePositions', {
							me: this
						});
					}.bind(this));
				}
			}
			
			db.insert(myTank, function(err, doc) {
				if (err) return;
				id = doc._id;
				socket.emit('handshake!', doc);
				post('*' + name + '* connected.');
			});
		});
/**
 * Adds the given note.
 *
 * @param note the note to be persisted
 * @param callback callback being executed
 */
function publicAdd(note, callback) {
    db.insert(note, function (err, newNote) {
        if (callback) {
            callback(err, newNote);
        }
    });
}
Example #11
0
	set : function (query) {
		settingsdb.loadDatabase();		
		settingsdb.insert(query, function (err, doc) {
			if(err) throw err;
			console.log('Setting inserted : ', doc);
		});	
	},
Example #12
0
function insert(doc) {
  var deferred = Q.defer();
  dataStore.insert(doc, function(err, newDoc){
    deferred.resolve(newDoc);
  });
  return deferred.promise;
}
Example #13
0
    groups.count({ _id:group_id }, function (err, count) {
        if(count > 0){
            if(callback)
                return callback("group already exist");
        }
        else {
            if(group_id != null){
                var doc = {
                    _id: group_id,
                    groupname: groupname,
                    users: [user_id]
                };
            }
            else {
                var doc = {
                    groupname: groupname,
                    users: [user_id]
                };
            }

            groups.insert(doc, function (err,newDoc) {
                if(err){
                    if(callback)
                        return callback(err);
                }
                else {
                    if(callback)
                        return callback(newDoc);
                }

            });
        }
    });
Example #14
0
 docs.map((old) => {
   var doc = {
     _id: old._id,
     superUser: old.superUser,
     blacklisted: false,
     perms: {
       level1: old.permissions.level1,
       level2: old.permissions.level2,
       level3: old.permissions.level3,
       nsfw: old.nsfw_permissions.allowed
     }
   }
   newPerms.insert(doc, function (err, doc) {
     if (err) {
       reject('Insertion failiure, ' + err)
     } else if (doc) {
       counter++
       if (counter >= count) {
         load.stop()
         Logger.info('Permission transfer complete, transferred ' + counter + ' documents.')
         count = 0
         counter = 0
         resolve()
       }
     }
   })
 })
Example #15
0
					isDisplayedPromise.done(function(result){
						if(result.toQueue){//tweet not found! queue it up!
							var queueTweet = processTweetData(result.data);
							tweetQueue_db.insert(queueTweet);
							console.log("queueing ", queueTweet.message);
						}
					});
app.post("/",function(req,res){
  var email = req.body.email;
  console.log(email);
  var doc = {email: email};
  db.insert(doc);
  res.end("Email Saved");
});
Example #17
0
    it('should end a current running task', function (done) {
        var now = moment();
        var oldStart = moment().subtract(1, 'hour');
        var name = 'mocha test';

        var db = new Datastore();

        var context = {
            isContext: true,
            db: db,
            options: {
                db: null,
                start: now,
                task: name
            }
        };

        var id = 1;
        db.insert({_id: id, start: oldStart}, function (err, newObj) {
            if (err) done(err);

            expect(newObj.start).to.eql(oldStart);
            expect(newObj.end).to.be.undefined;

            aptrac.start(context, function (err, context, newTask) {
                if (err) done(err);

                db.findOne({_id: id}, function (err, task) {
                    expect(now.isSame(task.end)).to.be.true;
                    done(err)
                })
            })
        });

    })
Example #18
0
app.post('/characters', function (req, res) {
	var character = req.body;
	charactersDb.insert(character, function (err, newDoc) {
		res.statusCode = 301;
		res.header('location', '/characters/' + newDoc._id).end();
	});
});
Example #19
0
app.use(get('/:email/:amount', function*(){

  var data = {
    email: this.email,
    amount: this.amount,
    time: new Date()
  };

  // Insert to database
  db.insert(data, function(err, doc){

    // send mail with defined transport object
    smtpTransport.sendMail(buildEmailOptions(data.email, data.amount, doc._id), function(error, response){

      if(error){
        console.log(error);
        this.body = {failed: true, error: error};
      }else{
        console.log("Message sent: " + response.message);
      }

    });

  });

  if ( this.amount > 0 ) {
    this.body = '<html><head><script type="text/javascript">setTimeout(function(){window.location="'+ config.targetFile +'";}, 3000);</script><title>Thank you!</title></head><body><h1>Payment was successful... download will begin shortly.</h1></body></html>';
  }

}));
Example #20
0
 addOrder = function (order, callback) {
     db.insert(order, function (err, inserted) {
         if (callback && typeof (callback) === 'function') {
             callback(err, inserted);
         }
     });
 };
Example #21
0
function insert(url, source, data, callback) {
  var key = _makeKey(url, source);
  cacheStore.insert({
    key: key,
    data: data
  }, callback);
}
Example #22
0
router.post('/register', function (req, res) {

    if (req.body!=undefined){

        var s = settings.getSettings();

        var guestData = req.body;
        guestData['msTimeAdded'] = new Date().getTime();
        guestData['eventName'] = s.eventName;
        guestData['docType'] = "guest";
        guestData['score'] = parseInt(guestData['score']);
        db.insert(guestData, function(err, doc){
            console.log("Inserted!");
            res.writeHead(200, {'content-type': 'application/json'});
            res.write(JSON.stringify(doc));
            res.end();

        });
    } else {
        res.writeHead(400, {'content-type': 'application/json'});
        res.write(JSON.stringify({error: "malformed request"}));
        res.end();
    }

});
function insertInDb(clip) {
  var $ = cheerio.load(clip);
  var $clip = $(clip);

  function _getModels() {
    var models = [];
    $clip.find('.actor a').each(function (i, item) {
      models.push({
        name: $(item).text(),
        link: $(item).attr('href')
      });
    });
    return models;
  }

  var movie = {
    title: $clip.find('.left > a').text(),
    aired: new Date($clip.find('.actor+div').text()),
    //rating: $clip.find('.rating').text(),
    //favs: $clip.find('.favs').text(),
    //comments: $clip.find('.comments').text(),
    models: _getModels(),
    poster: $clip.find('img').attr('src'),
    externalId: $clip.find('.left > a').attr('href')
  };
  console.log(movie);
  db.insert(movie, function (err, movie) {
    if (err) {
      console.log(err);
    }
    console.log(movie);
  });
}
Example #24
0
function initializeDB() {
  gAsyncCount = 0;
  
  startTime = process.hrtime();

  // nedb uses async callbacks so we will not time each operation but 
  // use globals to count when the last async op has finished
	for (var idx=0; idx < arraySize; idx++) {
   	var v1 = '12345'; //genRandomVal(); 
    var v2 = '23456'; //genRandomVal();
    
   	ndb.insert({ 
			customId: idx, 
			val: v1, 
			val2: v2, 
			val3: "more data 1234567890"
		}, function (err, newDoc) {   // Callback is optional
      if (++gAsyncCount == arraySize) {
        endTime = process.hrtime(startTime);
        var totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;
        var rate = arraySize * 1000 / totalMS;
        rate = rate.toFixed(2);
        console.log("load (insert) : " + totalMS + "ms (" + rate + ") ops/s");
        
        testperfFind();
      }
    });
   }
}
 }, function (err, docs) {
     if (docs.length === 0) {
         deckStorage.insert({
             '_id': username
         });
     }
 });
Example #26
0
						.on('end', () => {
							console.log("The file "+path+" has been converted succesfully.");
							picturesSizeDb.insert({unlink: fullConvertedPath, path:path});
							res.header('Cache-Control', config.cache);
							res.sendFile(fullConvertedPath, {root: __dirname});
							callback();
						})
Example #27
0
            }, function(err, docs) {
                if (err) {
                    return next({
                        status: 500,
                        message: err
                    });
                }
                if (!docs[0].isMaster) {
                    return next({
                        status: 401,
                        message: "Unauthorized"
                    })
                }
                datastore.insert(pledge, function(err) {
                    if (err) {
                        return next({
                            status: 500,
                            message: err
                        });
                    }

                    res.status(201).json({
                        pledge: pledge
                    });
                });
            });
Example #28
0
	 saveMovie: function(doc) {
	 console.log("save function");
	 	console.log(doc);
        db.insert(doc, function (err, newDoc) {
        console.log("inserted successfully..");	
        });
    },
Example #29
0
 addProduct = function (product, callback) {
     db.insert(product, function (err, inserted) {
         if (callback && typeof (callback) === 'function') {
             callback(err, inserted);
         }
     });
 };
Example #30
0
app.post("/humans", function(req, res) {
  var human = req.body;
  humansDb.insert(human, function (err, newDoc) {
    res.statusCode = 301;
    res.header("location", "/humans/"+newDoc._id).end();
  });

});