【问题标题】:LokiJS returns null database within moduleLokiJS 在模块内返回空数据库
【发布时间】:2019-06-17 16:10:45
【问题描述】:

我正在为 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
        });
    }
}

【问题讨论】:

    标签: javascript lokijs


    【解决方案1】:

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

    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-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 1970-01-01
      相关资源
      最近更新 更多