Skip to content

When data in lowdb is updated defaultData (object) also updated.Β #604

@chokchai

Description

@chokchai

I don't know if this is expected behavior or not. But it feels off for me.
It will cause issues when using defaultData multiple times.
(ex. multiple lowdb instances using the same defaultData)

ISSUES:

  • defaultData is used as a reference for data in lowdb object.
  • when data in lowdb is updated the defaultData object content is also updated.
  • please check the example typescript code below.
import {JSONFilePreset} from "lowdb/node"

const defaultData = {
    name: "ALICE",
}

const db = await JSONFilePreset("test.json", defaultData)

// db.data should be ALICE
console.log(db.data.name === "ALICE") // true

// update db.data to BOB
db.data.name = "BOB"

// db.data now is BOB
console.log(db.data.name === "BOB") // true

// defaultData should still be ALICE
console.log(defaultData.name === "ALICE") // false

// defaultData becomes BOB instead (unexpected)
console.log(defaultData.name === "BOB") // true

SOLUTION:

  • deep clone object
  • using structuredClone fixed it.
const db = await JSONFilePreset("test.json", structuredClone(defaultData))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions