typicode / lowdb

Simple and fast JSON database
MIT License
21.49k stars 923 forks source link

TypeError: db.defaults is not a function #505

Closed axi92 closed 3 years ago

axi92 commented 3 years ago

What am I doing wrong?

import {Low as low, JSONFile as FileSync} from 'lowdb';
const adapter = new FileSync('db.json');
const db = new low(adapter);
db.defaults({
  servers: []
})
  .value();

I got "type": "module", in my package.json so all needs to be import and no require() I tried to figure it out with that #487 but it did not help. Do I need lodash now? I just upgraded from 1.0.0

typicode commented 3 years ago

Hi @axi92

db.defaults doesn't exist in lowdb >=2, see https://github.com/typicode/lowdb/releases/tag/v2.0.0 for migration

Lodash is now optional.

You have the choice of using pure JavaScript or Lodash utility functions. If you don't want to rewrite your code too much or prefer Lodash, you can add it using: https://github.com/typicode/lowdb#lodash

axi92 commented 3 years ago

Ok ty that helped a little bit.

I use node 14 LTS and ||= is only since 15 available I tried it like this, but it did not work, it never gets the data loaded. It is overwriting the data because nothing gets loaded every time. And FileSync is not available so I used JSONFileSync.

import {Low as low, JSONFileSync as FileSync} from 'lowdb';
const adapter = new FileSync('testdb.json');
const db = new low(adapter);
console.log(db);

// Set some defaults
if(db.data === null){
  db.data = { servers: [] };
  db.write();
}

console.log(db);

Output:

$ node test.js 
Low { adapter: JSONFileSync {}, data: null }
Low { adapter: JSONFileSync {}, data: { servers: [] } }
typicode commented 3 years ago

Looks good :+1:

There's this example that should get you started with correct imports, etc... (I've updated it to make it clearer about Node >= 15 and ||=) https://github.com/typicode/lowdb#usage

There's also an examples/ directory