【问题标题】:calling javascript class method from another method from the same class从同一类的另一个方法调用 javascript 类方法
【发布时间】:2017-10-17 19:43:33
【问题描述】:

我正在尝试编写一个名为 Mongo 的包装类。当我在 insert() 中调用 getCollection() 时,出现“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;

如何实例化这个类,调用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);
        });
    })
})

【问题讨论】:

    标签: javascript node.js mongodb class


    【解决方案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);
        });
    }
    

    【讨论】:

    • getCollection() 内部呢?我是否也需要这样做('var self= this')?
    • 是的,您还需要将Mongo 类实例存储在getCollection 中,否则您与this. 一起使用的那些变量将具有未定义的值
    【解决方案2】:

    如下更新插入函数 -

    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类引用存储在一个变量中,然后使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-15
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 2011-01-14
      相关资源
      最近更新 更多