JSFiddle - React, Tailwind, and code Playground

by somekittens

JavaScript

'use strict';

function Helper(config) {
  //I get TypeError: Cannot set property 'mongo' of undefined on line 5
  this.mongo = require('mongodb');
  this.server = new this.mongo.Server(config.serverAddress, config.serverPort, config.serverParams);
  this.mdb = new this.mongo.Db(config.dbName, this.server, config.dbParams);
  /**
   * Takes care of rote work that every operation needs
   * coll is the name of the collection we're operating on
   * next is an optional callback.  If the operation returns results, they'll be
   *     passed to next.
   * operation contains the db operation that we want to execute
   */
  this.getCollection = function(coll, next, operation) {
    this.mdb.open(function(err, db) {
      db.collection(coll, function(err, collection) {
        operation(err, collection, function(err, results) {
          if(err) { console.error(err); }
          db.close();
          if(typeof next === 'function') {
            next(results);
          }
        });
      });
    });
  };
};

/**
 * Basic helper for database CRUD operations.
 * next is an optional argument that is executed after the async calls have
 * completed.  The results of the find query (if applicable) will be passed to it
 * AFTER the database is closed, so you can execute another db call.
 */
Helper.prototype = {
  insert: function(coll, query, next) {
    this.getCollection(coll, next, function(err, collection, after) {
      collection.insert(query, after);
    });
  },
  find: function(coll, query, next) {
    this.getCollection(coll, next, function(err, collection, after) {
      collection.find(query).toArray(after);
    });
  },
  update: function(coll, criteria, update, params, next) {
    this.getCollection(coll, next, function(err, collection, after) {
      collection.update(criteria, update, params, after);
    });
  },
  remove: function(coll, query, next) {
    this.getCollection(coll, next, function(err, collection, after) {
      collection.remove(query, after);
...