techfort / LokiJS

javascript embeddable / in-memory database
http:/techfort.github.io/LokiJS
MIT License
6.71k stars 478 forks source link

TypeError: Cannot read property 'collections' of null #906

Closed chuongle closed 2 years ago

chuongle commented 2 years ago

Today I encountered a weird issue with LokiJS. For whatever reason, the main db file (metadata) got wiped, the file is still there but the content is empty. So when the application started again, I got the TypeError: Cannot read property 'collections' of null error. The issue is I can catch any of these error. The only reason I am aware of this error is because I have sentry setup and it automatically caught it.

Here is the code I use:

try {
  const db = new Loki('test.db', {
    adapter: new LokiFsStructuredAdapter(),
    autosave: true,
    autosaveInterval: 5000
  });

  db.loadDatabase({}, (error) => {
    if (error) {
      console.log('fail to load error: ', error);
    } else {
      console.log('successfully load db')
      // set up collections and insert data
    }
  });  
} catch (error)
  console.log('error', error);
}

Here is the full error:

TypeError: Cannot read property 'collections' of null
    at Interface.eval (webpack:///./node_modules/lokijs/src/loki-fs-structured-adapter.js?:153:31)
    at Interface.emit (events.js:327:22)
    at Interface.EventEmitter.emit (domain.js:467:12)
    at Interface.close (readline.js:424:8)
    at ReadStream.onend (readline.js:202:10)
    at ReadStream.emit (events.js:327:22)
    at ReadStream.EventEmitter.emit (domain.js:467:12)
    at endReadableNT (internal/streams/readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)

I am not sure what is going on here. Is there a right way of handling error that I am missing?

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Losses commented 1 year ago

One case may trigger this problem: you are creating a collection but didn't write anything into it, this is a bug of the loki-fs-structured-adapter and we are trying to fix it.

Losses commented 1 year ago

BTW, there's a fixed version of the adapter, but it was refactored with TypeScript.

https://github.com/recative/studio/blob/main/packages/loki-fs-structured-adapter/main.ts

chuongle commented 1 year ago

@Losses Thank you for the update!!!