Thursday 18 May 2017

calling javascript class method from another method from the same class

I'm trying to write a wrapper class called Mongo. When I call getCollection() inside insert(), but I'm getting 'TypeError: this.getCollection is not a function'.

const mongoClient = require('mongodb').MongoClient;
const connectionString = process.env.MONGODB_CONNECTION_STRING;
const mongoOptions = {
    connectTimeoutMS: 500,
    autoReconnect: true
};

function Mongo(dbName, collectionName) {
    this.dbName = dbName;
    this.collectionName = collectionName;
    this.db = null;
    this.collectionCache = {};

    this.getDB = function () {
        return new Promise(function (resolve, reject) {
            if (this.db == null) {
                mongoClient.connect(connectionString, mongoOptions, function (err, db) {
                    if (err) reject(err);
                    this.db = db.db(this.dbName);
                    resolve(this.db);
                });
            } else {
                resolve(this.db);
            }
        });
    };

    this.getCollection = function () {
        return new Promise(function (resolve, reject) {
            if (this.collectionName in this.collectionCache) {
                resolve(this.collectionCache[this.collectionName]);                
            } else {
                getDB().then(function(db) {
                    db.collection(this.collectionName, function (err, collection) {
                        if (err) reject(err);
                        this.collectionCache[this.collectionName] = collection;
                        resolve(collection);                    
                    });
                }, function (err) {
                    reject(err);
                });
            }
        });
    };

    this.insert = function(docs) {
        return new Promise(function (resolve, reject) {
            this.getCollection().then(function(collection) {
                collection.insert(docs, function(err, results) {
                    if (err) reject(err);
                    resolve(results);
                });
            });
        }, function (err) {
            reject(err);
        });
    }
}


module.exports = Mongo;

How this class is instantiated, and the insert method is called.

const assert = require('assert');
const Mongo = require('../data/mongo');

describe('MongoTest', function() {
    it('TestInsert', function() {
        var mongo = new Mongo('testdb', 'humans');

        var testDoc = {
            _id: 1100,
            name: 'tommy',
            tags: ['cool', 'interesting']
        };

        mongo.insert(testDoc).then(function(result){
            assert.equal(result._id, 1100);
        });
    })
})



via gotomstergo

No comments:

Post a Comment