How to use the mongodb.Collection function in mongodb

To help you get started, we’ve selected a few mongodb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github kilianc / node-apiserver / examples / instagram / server.js View on Github external
mongodbDb.open(function (err, mongodbClient) {
  if (err) {
    console.error('\n ☹ Cannot connect to mongodb: %s\n'.red, err.message)
    return
  }
  var collections = {
    photos: new mongodb.Collection(mongodbClient, 'photos')
  }

  // Static server allocation
  connect().use(connect.static(__dirname + '/public')).listen(8000, function () {
    console.info('\n ✈ Static server listening at http://localhst:8000'.green)
  })

  // ApiServer allocation
  var apiServer = new ApiServer({
    timeout: 1000,
    domain: 'localhost'
  })

  // middleware
  apiServer.use(/^\/list$/, ApiServer.httpAuth({
    realm: 'ApiServer Example',
github acmeair / acmeair / acmeair-webapp-nodejs / routes / index.js View on Github external
getFlightSegmentByOriginPortAndDestPort(fromAirport, toAirport, function(error, flightsegment) {
		if (error) throw error;
		
		logger.debug("flightsegment = " + JSON.stringify(flightsegment));
		if (!flightsegment) {
			callback(null, null, null);
			return;
		}
		
		var collection = new mongodb.Collection(dbClient, 'flight');
		
		dayAtMightnight = new Date(flightDate.getFullYear(), flightDate.getMonth(), flightDate.getDate());
		milliseconds = 24 /* hours */ * 60 /* minutes */ * 60 /* seconds */ * 1000 /* milliseconds */;
		nextDayAtMightnight = new Date(dayAtMightnight.getTime() + milliseconds);

		var cacheKey = flightsegment._id + "-" + dayAtMightnight.getTime();
		if (settings.useFlightDataRelatedCaching) {
			//var cacheKey = flightsegment._id + "-" + dayAtMightnight.getTime();
			var flights = flightCache.get(cacheKey);
			if (flights) {
				logger.debug("cache hit - flight search, key = " + cacheKey);
				callback(null, flightsegment, (flights == "NULL" ? null : flights));
				return;
			}
			// else - fall into loading from data store
			logger.debug("cache miss - flight search, key = " + cacheKey + " flightCache size = " + flightCache.size());
github azat-co / fullstack-javascript / 11-db / collections.js View on Github external
client.collectionNames(function(error, names){
    if(error) throw error;

    //output all collection names
    log("Collections");
    log("===========");
    var lastCollection = null;
    names.forEach(function(colData){
      var colName = colData.name.replace(dbName + ".", '')
      log(colName);
      lastCollection = colName;
    });
    if (!lastCollection) return;
    var collection = new mongodb.Collection(client, lastCollection);
    log("\nDocuments in " + lastCollection);
    var documents = collection.find({}, {limit:5});

    //output a count of all documents found
    documents.count(function(error, count){
      log("  " + count + " documents(s) found");
      log("====================");

      // output the first 5 documents
      documents.toArray(function(error, docs) {
        if(error) throw error;

        docs.forEach(function(doc){
          log(doc);
        });
github acmeair / acmeair / acmeair-webapp-nodejs / routes / index.js View on Github external
function validateCustomer(username, password, callback /* (error, boolean validCustomer) */) {
	var collection = new mongodb.Collection(dbClient, 'customer');
	  
	collection.find({_id: username}).toArray(function(err, docs) {
		if (err) callback (err, null);
		var customer = docs[0];
		callback(null, customer.password == password);
	});
};
github Lapple / ErrorBoard / modules / stats.js View on Github external
.open(function ( err, client ) {
        if ( err ) {
          console.error( 'Error: %s\nExiting.', err.message );
          process.exit();
        }
        this.collection = new mongodb.Collection( client, this.collectionName );
      }.bind( this ));
github anandtrex / collabdraw / server.js View on Github external
var pageNo = parseInt(data.page);
            var canvasName = data.room;
            console.log("canvas name", data.room);
            console.log("page", data.page);

            if (!allPaths[canvasName] || !allPaths[canvasName][pageNo]) {
                if (!allPaths[canvasName]) {
                    console.log("INITIALIZING allPaths[" + canvasName + "] to []");
                    allPaths[canvasName] = [];
                }

                //console.log("INITIALIZING allPaths[" + canvasName + "][" + pageNo + "] to []");
                //allPaths[canvasName][pageNo] = [];

                var collection = new mongodb.Collection(db, socket.room);
                var nPages = 0;
                var nPagesGot = false;

                if (!allPaths[canvasName]["nPages"]) {
                    console.log("GETTING number of pages");

                    collection.find({
                        type : "files_info",
                        canvas_name : canvasName,
                    }).toArray(function(err, results)
                    {
                        if (err)
                            throw err;

                        if (results.length == 0) {
                            nPages = 1;
github acmeair / acmeair / acmeair-webapp-nodejs / routes / index.js View on Github external
function cancelBooking(bookingid, userid, callback /*(error)*/) {
	var collection = new mongodb.Collection(dbClient, 'booking');
	
	collection.remove({"_id" : bookingid, "customerId" : userid}, null, function(err, removed) {
		callback(err);
	});
}
github cfpb / ec2mapper / ec2mapper-main.js View on Github external
app.get("/vpc/info", function(req, res) {
  res.writeHeader(200, {"Content-type": "application/json"});
  var vpc_info = new mongo.Collection(ec2db, 'vpc_info');
  vpc_info.find({}).toArray(function(err, items) {
    var result = {};
    _.each(items, function(item) {
      delete item["_id"];
      result[item.id] = item; 
    });
    res.end(JSON.stringify(result));
  });    
});
github i18next / i18next-node / backends / mongoDb / sync.js View on Github external
var finish = function() {
                    self.client = client;
                    self.isConnected = true;
                    
                    self.resources = new mongo.Collection(client, options.resCollectionName);

                    if (callback) callback(null, self);
                };
github mwaylabs / bikini / server / mongodb_rest.js View on Github external
update: function(req, res, fromMessage) {
            var name = req.params.name;
            var doc  = req.body;
            var id   = this.toId(req.params.id || doc._id);
            if (typeof id === 'undefined' || id === '') {
                return res.send(400, "invalid id.");
            }
            doc._id   = id;
            doc._time = new Date().getTime();
            var collection = new mongodb.Collection(this.db, name);
            collection.update(
                { "_id" : id },
                doc,
                { safe:true, upsert:true },
                function(err, n) {
                    if(err) {
                        res.send("Oops!: " + err);
                    } else {
                        if (n==0) {
                            res.send(404, 'Document not found!');
                        } else {
                            var msg = {
                                method: 'update',
                                id: doc._id,
                                time: doc._time,
                                data: doc