Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chokchai opened this issue Dec 29, 2024 · 1 comment
Open

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

chokchai opened this issue Dec 29, 2024 · 1 comment

Comments

@chokchai
Copy link

chokchai commented Dec 29, 2024

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))
@IV-R
Copy link

IV-R commented Jan 9, 2025

Import { JSONFilePreset } from 'lowdb/node';

const defaultData = {
name: 'АЛІСА',
};

// Створення глибокої копії defaultData
const defaultDataCopy = JSON.parse(JSON.stringify(defaultData));

const db = await JSONFilePreset('test.json', defaultDataCopy);

// Оновлення db.data
db.data.name = 'БОБ';

// Перевірка значень
console.log(db.data.name); // 'БОБ'
console.log(defaultData.name); // 'АЛІСА'

Пояснення:
Проблема виникає через те, що defaultData передається за посиланням в lowdb. Зміни в db.data впливають на оригінальний об’єкт defaultData. Щоб уникнути цього, створіть глибоку копію defaultData за допомогою JSON.parse(JSON.stringify(defaultData)).

Такий підхід гарантує, що зміни в db.data не вплинуть на оригінальний об’єкт defaultData.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants