"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach.

I have created typescript objects that extend a Document base class with mandatory _id and _rev fields. Is this the right direction for me? Am I even close?

Below is my implementation of a Document base class that seems suitable for a PouchDB database-

import PouchDB from 'pouchdb';

// Base class for all objects persisted in the database
export class Document {

    readonly type: string;
    readonly _id: string;
    private _rev?: string; // assigned by the database upon insertion

    constructor(type: string, id_suffix?: string) {
        this.type = type;
        let unique_id: string = uuid();

        if (id_suffix === undefined) {
            this._id = '${type}_${unique_id}'
        }
        else {
            this._id = '${type}_${id_suffix}_${unique_id}'
        }
    }
}

It seems I can successfully insert it into the database:

let db = new PouchDB('my-database');
let mydoc = new Document('mydoc');

db.put(mydoc);

let output = db.get(mydoc._id); //Promise<PouchDB.Core.IdMeta & PouchDB.Core.GetMeta>

Could anyone assist me in retrieving my object?

Answer №1

Seems like this is functioning as expected...

import PouchDB from 'pouchdb';

// Base class for objects stored in the database
export class Document {

    readonly type: string;
    readonly _id: string;
    private _rev?: string; // set by database upon insertion

    constructor(type: string, id_suffix?: string) {
        this.type = type;
        let unique_id: string = uuid();

        if (id_suffix === undefined) {
            this._id = '${type}_${unique_id}'
        }
        else {
            this._id = '${type}_${id_suffix}_${unique_id}'
        }
    }
}

db.put(t);

let output = db.get<Document>(t._id).then(function (doc){
    let x: Document = doc;
    return x;
})

Answer №2

Just a friendly reminder: when you convert the return value (e.g. as Document) from a plain object (Pouchdb store JSON objects), the prototype is lost. This means that you will need to create a new instance from scratch.

For instance:

let output = db.get<Document>(t._id).then(function (doc){
    return new Document(
        doc.type,
        doc. id_suffix
    );
})

Alternatively, as recommended here, you can use Object.assign (although I have not personally tested this method).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes obser ...

What are the steps to activating components in vue.js?

Why do I always see the UsersList.vue component when opening any URL? Is it because I include it in the App.vue? If I change it to <router-view/>, I only see an empty page. How can I resolve this issue? Also, how can I navigate from ListView to Detai ...

Tips for modifying the data type of a property when it is retrieved from a function

Currently, I have a function called useGetAuthorizationWrapper() that returns data in the format of { data: unknown }. However, I actually need this data to be returned as an array. Due to the unknown type of the data, when I try to use data.length, I enc ...

I seem to have mistakenly bound my conditional class to everything that was iterated in my object. Can you help me identify what I did wrong?

I recently received an object from a Last.FM API call containing the last 100 songs I listened to. If there is a song currently playing, there is a nowplaying flag on the first item in the object. I'm attempting to bind a class to the markup if this ...

An issue has occurred with the NullInjector, specifically regarding the AppModule and Storage in Ionic 4

When attempting to launch my Ionic app using npm start, an error message appears stating "NullInjectorError: No provider for Storage!". I have already included Storage in the app.module.ts file as shown below: imports: \[ BrowserModule, IonicModule ...

Unable to display data from vuex getters in the story

My MongoDB database contains: user:{ matchesList:[{ kdList:String, winsMatchesList:String }] After creating a Vuex.Store with some getters, I have: matchesList: state => state.matchesList, matchesListKD: state =&g ...

Having trouble installing memlab using the npm package

Recently, I made an attempt to install the memlab library from Meta's GitHub. Initially, when I installed it without using the -g flag, the installation was successful. However, I encountered an issue where I could not execute any of the memlab comman ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...

Showcasing an image using a base64 string in Vue.js

I received a base64 string image from the backend server and now I want to convert it into an actual image to display. Here is what I have done: JavaScript let previewLogo = new Image(); previewLogo.src = `data:image/png;base64,${fileList[i].file}`; HTML ...

Ways to showcase corresponding information for an item contained within an array?

I'm working with a function that is designed to retrieve specific descriptions for objects nested within an array. The purpose of the function (findSettings()) is to take in an array (systemSettings) and a key (tab12) as arguments, then use a switch s ...

Vue component updating its model only upon input element losing focus

I'm a beginner with vue and I'm currently working on incorporating an ajax search feature that triggers when a keyup event occurs. I have noticed that the model only updates when the input element loses focus. Sample HTML Code: <input name=" ...

Exploring the dynamic duo of Google Spreadsheets and Vue

Hey there! I've been using the awesome library found at https://github.com/theoephraim/node-google-spreadsheet to interact with Google Sheets. The authentication process seems to be working fine, but when I attempt to retrieve the sheets for further ...

"Incorporating the node_modules folder into the Express.js compilation process

Is there a way to automatically include dependencies during Express.js compilation, similar to building a React project? I want to avoid dealing with dependencies after the build process. Any suggestions on how to achieve this? I have not attempted any so ...

Tips for dynamically implementing a pipe in Angular 5

In my Angular application, I have implemented a filter using a pipe to search for option values based on user input. This filter is applied at the field level within a dynamically generated form constructed using an ngFor loop and populated with data from ...

Setting default values in Vuejs from browser URL parameters

I found a URL link that directs to different cities: Below is the Vue template code: <template> <ul> <li v-for="city in states" :key="city.id" :id="city.id" v-bi ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

The primeVue menubar's active/focused item highlighting feature is not functioning correctly

Currently, we are in the process of developing an electron-based application with the front end primarily coded using Vue.js and primeVue. As a novice, I am encountering issues with the menubar component from primeVue. The problem is that no matter which i ...

Utilizing VueJS and Lodash: The technique for extracting an array of objects exclusively featuring a specific key string

I am attempting to extract certain data from an Object that has a string _new attached to it. Explore the code on Codesandbox: https://codesandbox.io/s/vibrant-bardeen-77so1u?file=/src/components/Lodash.vue:0-353 This is what my data looks like: data.j ...

Discover the steps for retrieving the <div> element using the swiper API

Link to my page: Click here Design reference: View design The design requires flexing the 2 arrow buttons, but these elements are missing in the code(source: autoplay swiper). How can I align them to the right-bottom corner? <div class="flex" ...