我正在为NodeJS应用程序创建一个noSQL数据库。我希望数据库作为它自己的类存在。但是,在模块内移动数据库初始化代码后,它不再工作。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
});
}
}发布于 2019-06-18 00:55:44
您的作用域在回调中发生更改。最简单的方法是使用箭头函数:
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
});https://stackoverflow.com/questions/56635149
复制相似问题