从同一个类的另一个方法调用javascript类方法

时间:2017-05-18 06:30:33

标签: javascript node.js mongodb class

我试图编写一个名为Mongo的包装类。当我在insert()中调用getCollection()时,我得到' TypeError:this.getCollection不是函数'。

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;

如何实例化此类,并调用insert方法。

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);
        });
    })
})

2 个答案:

答案 0 :(得分:1)

如果您正在调用getCollection函数,this不再引用Mongo对象,则它指的是您作为参数传递的回调函数到Promise

有很多方法可以解决这个问题。以下是一些:

保持对象的引用:

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

绑定上下文:

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

答案 1 :(得分:0)

更新您的插入功能,如下所示 -

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

您收到此错误是因为您在回调函数内调用getCollection,其中this未引用Mongo类。因此,您需要将Mongo类引用存储在变量中,然后使用它。

相关问题