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