0

我正在为 NodeJS 应用程序创建一个 noSQL 数据库。我希望数据库作为自己的类存在。但是,在模块内移动我的数据库初始化代码后,它不再起作用。LokiJS 无法加载数据库,我无法创建集合。加载数据库的结果为 null,this.db 未定义,尝试获取集合会生成Uncaught TypeError: Cannot read property 'getCollection' of undefined.

module.exports = Database;
function Database() {
    this.db;
    this.videos;
    this.playlists;

    this.init = function () {
        const loki = require("lokijs");
        const lfsa = require('../../node_modules/lokijs/src/loki-fs-structured-adapter.js');

        var adapter = new lfsa();
        this.db = new loki(`${localPath}db.json`, { adapter: adapter, autoload: true, autosave: true, autosaveInterval: 4000 });
        this.db.loadDatabase({}, function (result) {
            console.log(result); // This is null
            alert(this.db); // This is undefined
            alert(this.db.getCollection("SampleCollection")); // Uncaught TypeError: Cannot read property 'getCollection' of undefined
        });
    }
}
4

1 回答 1

0

您的范围在回调中发生变化。最简单的方法是使用箭头函数:

this.db.loadDatabase({}, result => {
            console.log(result); // This is null
            alert(this.db); // This is undefined
            alert(this.db.getCollection("SampleCollection")); // Uncaught TypeError: Cannot read property 'getCollection' of undefined
        });
于 2019-06-17T16:55:44.060 回答