"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

Issues with manipulating state using TypeScript Discriminated Unions"Incompatibility with setState

Imagine having a unique type structure like the one shown below: export type IEntity = ({ entity: IReport setEntity: (report: IReport) => void } | { entity: ITest setEntity: (test: ITest) => void }); Both the entity and setEntity fun ...

What could be the reason that Vue is not evaluating anything when the directive @click is specified as "true && method"?

Consider the following scenario: LandingPage.vue <template> <button @click="handleClick">Click Me</button> </template> <script> export default { methods: { handleClick() { this.$emit("click"); } } }; < ...

Encountering issues when trying to import const enums in a webpack project using babel

Currently, I am working on a react project that was initially created using create-react-app. However, we later ejected and made extensive modifications to the webpack configuration. My current struggle lies in importing const enums from external libraries ...

Tips for incorporating a development server proxy with Ionic and Vue

I am interested in utilizing the Proxies feature of Ionic in my Vuejs project built with Ionic. While I have come across solutions for proxy issues in Ionic + Angular and Vue + Webpack projects, I have yet to find a resolution for my specific Ionic + Vue ...

Using Vue.js, learn how to target a specific clicked component and update its state accordingly

One of the challenges I'm facing is with a dropdown component that is used multiple times on a single page. Each dropdown contains various options, allowing users to select more than one option at a time. The issue arises when the page refreshes afte ...

Unexpected error arises in Typescript despite code functioning properly

As part of a practice project where I'm focusing on using webpack, ES6, npm and Typescript implementation, I have successfully set up loaders for 'awesome-typescript-loader' and 'babel-loader', which are bundling the code properly. ...

"Exploring the best way to open a new tab in Angular from a component

I am working on a simple Angular application with two components. My goal is to open one component in a new tab without moving any buttons between the components. Here is an overview of my application setup: Within my AppComponent.html file, there is a b ...

Various types of generics within an object

Is there a way to achieve different types for the nested K type within a type like MyType? Here's an example: type Config<K> = { value: K; onUpdate: (value: K) => void; } type MyType<F extends string> = { [K in F]: <V>() =& ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Is it possible to assign an alternative name for the 'require' function in JavaScript?

To ensure our node module is executable and includes dependencies for requiring modules at runtime, we utilize the following syntax: const cust_namespace = <bin>_require('custom-namespace'); This allows our runtime environment to internal ...

Exploring the contrast of && and ?? in JavaScript

My current focus is on utilizing the Logical AND && and Nullish coalescing operator ?? in handling conditional rendering of variables and values. However, I find myself struggling to fully comprehend how these operators function. I am seeking clar ...

Issue with ng-multiselect-dropdown where clearing selected items programmatically does not visually work as expected

Utilizing the ng-multiselect-dropdown, I have encountered an issue where deselecting an option within the object itself clears the selected items visually and in the variable array. However, when programmatically clearing the selectedItems, the variable a ...

Troubleshooting VueJS: Imported JS file function fails to trigger

We are currently developing a web application utilizing Vue JS and PHP, with limited experience in Vue JS. The backend is functioning properly, able to retrieve data as JSON through the API. However, when attempting to display a static array before queryin ...

The error message "SyntaxError: Cannot use import statement outside a module" popped up while working with discord.js, typescript, heroku

// Necessary imports for running the discord bot smoothly import DiscordJS, { TextChannel, Intents, Message, Channel, NewsChannel, ThreadChannel, DiscordAPIError } from 'discord.js' type guildTextBasedChannel = TextChannel | NewsChannel | ThreadC ...

A guide on crafting a type definition for the action parameter in the React useReducer hook with Typescript

In this scenario, let's consider the definition of userReducer as follows: function userReducer(state: string, action: UserAction): string { switch (action.type) { case "LOGIN": return action.username; case "LOGOUT": return ""; ...

Using Express middleware in a TypeScript Express application

I'm currently converting the backend of an ExpressJS application to Typescript. While working on the auth.routes.ts file, I encountered an issue with the middleware (authMiddleware). It seems like there might be a typing error, as the same code in the ...

Using Vue.js to iterate over a list of items and accessing specific array objects by their unique identifier

My JSON array of objects has the following structure: https://i.sstatic.net/1IUVE.png When generating a <ul>, I need to fetch an ID from an API for each <li>: <ul> <li v-for="genre in movie.genre_ids"> {{ genre }} ...

Is bundling a Node.js backend a wise decision or a mistake?

Just a thought that crossed my mind - I understand the advantages of bundling client-side code, but what about bundling server-side code with Browserify/Webpack? Is this considered a best practice? ...

Observable in RxJS with a dynamic interval

Trying to figure out how to dynamically change the interval of an observable that is supposed to perform an action every X seconds has been quite challenging. It seems that Observables cannot be redefined once they are set, so simply trying to redefine the ...

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...