首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LokiJS在模块内返回null数据库

LokiJS在模块内返回null数据库
EN

Stack Overflow用户
提问于 2019-06-18 00:10:45
回答 1查看 387关注 0票数 0

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

代码语言:javascript
复制
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
        });
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-18 00:55:44

您的作用域在回调中发生更改。最简单的方法是使用箭头函数:

代码语言:javascript
复制
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
        });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56635149

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档