简体   繁体   中英

IndexedDB: How to prevent long int type being stored as string?

The IndexedDB has weird behaviour. When I tried to store long int number, it is stored as string . This will mess up the indexing, especially when I want to sort the data.

Example:

const data: {
  id: string,
  dateCreated: (new Date()).valueOf() //this is long type milliseconds
}

It is stored as "1674874732259" string inside the IndexedDB .

How do I prevent this?


This Is How I Store The Data

I use idb library to do it, write the async function much neater:

  async upsert(data: Note) {
    try {
      const db = await this.dbPromise;
      const tx = db.transaction(this.tableName, 'readwrite');
      const store = tx.objectStore(this.tableName);
      store.put(data);
      await tx.done;
    } catch (err) {
      return undefined;
    }
  }

DETAILED

  export const millisecondsNow = () => new Date().valueOf();

  async createNew() {
    const now = millisecondsNow();

    const newNote = {
      id: generateUUID(),
      title: 'Untitled',
      content: '',
      dateCreated: now,
      lastUpdated: now,
      status: 'ACTIVE',
      tags: '',
      userId: this.auth.auth.value.id,
    } as Note;

    await this.db.note.upsert(newNote);
    this.addList(newNote);
    this.sync.pushToSyncOutQueue(newNote);
  }

  async upsert(data: Note) {
    try {
      const db = await this.dbPromise;
      const tx = db.transaction(this.tableName, 'readwrite');
      const store = tx.objectStore(this.tableName);
      store.put(data);
      await tx.done;
    } catch (err) {
      return undefined;
    }
  }

This is the data stored in the database:

数据库

Note that the last entry is number, this is because my application sync-in a note from a Node server which has number type as the lastUpdated type. Somehow saving the incoming data from my server makes the lastUpdated column into number type.

Assigning the lastUpdated and dateCreated with 0 (number) will save the data successfully. It has a number type.


DEBUGGING SCREENSHOT

See this screenshot:

调试截图

Look at the value of the newNote at the right side of the image, inside the scope. This is the state of the object just before saving into the database. The lastUpdated and dateCreated are numbers.

I fixed this by changing the millisecondsNow() method into this:

export const millisecondsNow = () => +(new Date().valueOf());

By adding + sign which make sure that this returns number. To be honest I do not know how this solution even works. The new Date().valueOf() is already returning number.

Maybe someone can explain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM