I am creating a noSQL database for a NodeJS application. I want the database to exist as its own class. However, after moving my database initialization code inside the module it no longer works. LokiJS fails to load the database and I am unable to create collections. The result of loading a database is null, this.db is undefined and attempting to get a collection produces an 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
});
}
}
Your scope changes in the callback. The simplest way would be to use an arrow function instead:
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
});