typicode / lowdb

Simple and fast JSON database
MIT License
21.3k stars 918 forks source link

Can't 'set' database in `db.update` #590

Closed Timmiej93 closed 3 months ago

Timmiej93 commented 3 months ago

I have a basic setup like this:

{
  "entries": [
    {
      "key": "var"
      "..."
    }
  ]
}

I can push entries like this:

await db.update(({ entries }) => {
  entries.push({
    key: "value",
    ...
  })
})

I can also set the database like this:

db.data.entries = [
  {
    key: "value"
  }
]
await db.write()

But I can't set the database like this:

await db.update(({ entries }) => {
  entries = []
  // or
  return entries = []
})

Is this something I'm doing wrong, or is this a bug?

typicode commented 3 months ago

Hi,

entries.push() // mutates the array
entries = [] // replaces the variable value

await db.update((data) => {
  data.entries = [] // will mutate the data object and replace the entries value
})

// or
await db.update(({ entries }) => {
  entries.length = 0 // truncates the array
})
Timmiej93 commented 3 months ago

I figured it had to be something like that, since entries.push() did work. Thanks for clarifying!