LokiJS returns 模块内的空数据库

LokiJS returns null database within module

我正在为 NodeJS 应用程序创建一个 noSQL 数据库。我希望数据库独立存在 class。但是,在将我的数据库初始化代码移入模块后,它不再有效。 LokiJS 无法加载数据库,我无法创建集合。加载数据库的结果为空,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
        });
    }
}

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

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