Customizable mongoDB database collection

Is there a more efficient way to make calls to different collections based on a function parameter? I'm exploring the possibility and if it's not feasible, I'll handle it case by case.

Currently, I have this code and the goal is to have a unified create method for all three collections, as initially planned. However, TypeScript throws an error stating "This expression is not callable. Each member of the union type 'my 3 types' has signatures, but none of those signatures are compatible with each other." when calling insertOne (the usage of this[collection] is correct).

import { Collection, Db, InsertOneResult, ObjectId } from "mongodb";

export type L1CategoryDocument = L1Category & {
    _id: ObjectId;
};

export type L2CategoryDocument = L2Category & {
    _id: ObjectId;
};

export type L3CategoryDocument = L3Category & {
    _id: ObjectId;
};

export class CategoryClient {
    private l1: Collection<L1CategoryDocument>;

    private l2: Collection<L2CategoryDocument>;

    private l3: Collection<L3CategoryDocument>;

    constructor(db: Db) {
        this.l1 = db.collection("l1");
        this.l2 = db.collection("l2");
        this.l3 = db.collection("l3");
    }

    async create(collection: "l1", category: L1Category): Promise<InsertOneResult>;
    async create(collection: "l2", category: L2Category): Promise<InsertOneResult>;
    async create(collection: "l3", category: L3Category): Promise<InsertOneResult>;
    async create(
        collection: "l1" | "l2" | "l3",
        category: L1Category | L2Category | L3Category,
    ): Promise<InsertOneResult> {
        return this[collection].insertOne(category);
    }
}

Answer №1

It is advisable to group similar documents with matching content and structure into a single collection for improved querying and management efficiency. In your scenario, consider organizing your hierarchical structure within one collection using a category field. The $graphLookup operation can then be utilized to navigate the tree and retrieve relevant documents.

db.collection.aggregate([
  {
    "$match": {
      level: "L1"
    }
  },
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": "$_id",
      "connectFromField": "_id",
      "connectToField": "parent",
      "as": "children"
    }
  }
])

Try it out on Mongo Playground

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 program encountered an error stating that "Articles" is not defined

Two schemas are defined in my program. The first one works perfectly: var mongoose = require('mongoose'), Schema = mongoose.Schema; var NewsSchema = new Schema({ name: String, route: String, remoteURL: String, artic ...

What is the process for converting a buffer into an image file?

I am struggling with retrieving images stored in GridFS and converting them into a buffer using the code I have written. However, I'm unable to find proper documentation on how to render an image from this buffer within the MEAN stack environment. My ...

Arrange the columns in Angular Material Table in various directions

Is there a way to sort all columns in an Angular material table by descending order, while keeping the active column sorted in ascending order? I have been trying to achieve this using the code below: @ViewChild(MatSort) sort: MatSort; <table matSort ...

The custom component is not updating the NgIf directive in HTML even though it receives a boolean variable

I am struggling with a custom component that includes an *ngIf in its view to handle a boolean variable, but for some reason the *ngIf directive is not working. Here is the code snippet: Component @Input('title') titleText; @Input('backButt ...

Depend on a mapping function to assign a value to every option within a discriminated union

While utilizing all variations of a discriminated union with conditional if statements in TypeScript, the type is narrowed down to the specific variant. To achieve the same effect by expressing the logic through a mapping from the discriminant to a funct ...

Configuring the React Typescript router to support username-based URLs should be done in a way that does not cause conflicts with other routes

I am looking to display a user's profile on a URL format such as www.domain.com/<userName> and load the component ShowProfile. I want to ensure that terms is not mistaken for a username, so if I visit www.domain.com/terms, I do not want to load ...

Is there a way to ensure that the return type of a generic function is always optional in Typescript?

Is there a way to ensure the return type is always optional from a generic return type in functions? I specifically need the return types (data & error) to be optional at all times since one of them will always be undefined. TypeScript declarations i ...

What is the best way to create a mongoose schema that can only be edited once?

Currently, I am in the process of developing a bidding application. The mongoose schema used for this particular app is structured as follows: const bidSchema = new mongoose.Schema({ name: String, price : Number, description: String, l ...

Having trouble accessing previously submitted form values in Angular

When I try to update the form, I notice that my meetupform.controls.day array is not retaining the previously selected values app.component.html <div *ngIf="meetupForm.controls.recurring.value==='weekly'"> <mat-checkbox (change)="o ...

Verifying callback type in Typescript based on another argument's validity

There is a JavaScript function that I am working with: const fn = (cb, param) => { cb(param); }; This function is meant to be called in two ways within TypeScript: const cb0 = () => {}; fn(cb0); const cb1 = (param: string) => { }; fn(cb1, &a ...

When data is saved to the MongoDB collection, any outdated data is sent to the res() function

Despite everything seemingly running smoothly, the data I receive in res() seems to be lagging by one step. After countless rewrite attempts, I am unable to pinpoint the root cause of the issue. Here is a snippet of the backend code written on express.js, ...

Having trouble retrieving information from Node.js service in AngularJS 2

I am currently expanding my knowledge of Angular and attempting to retrieve data from a node js service using Angular 2 services. When I access the node js services directly from the browser, I can see the results. However, when I attempt to fetch the dat ...

Retrieve fresh information every 30 seconds utilizing the useQuery hook in React

I am utilizing '@tanstack/react-query' to retrieve data in my React + Typescript application. Below is a snippet of my code, where I aim to fetch metric data every 30 seconds import { useQuery } from '@tanstack/react-query'; import ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...

Guide to mocking the 'git-simple' branchLocal function using jest.mock

Utilizing the simple-git package, I have implemented the following function: import simpleGit from 'simple-git'; /** * The function returns the ticket Id if present in the branch name * @returns ticket Id */ export const getTicketIdFromBranch ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

Is it feasible to securely remove an item from an array within an object without the need for any assertions in a single function?

My interest in this matter stems from curiosity. The title may be a bit complex, so let's simplify it with an example: type ObjType = { items: Array<{ id: number }>; sth: number }; const obj: ObjType = { sth: 3, items: [{ id: 1 }, { id: 2 } ...

"Encountering issues with the functionality of two Angular5 routers

main.component.html [...] <a routerLink="/company-list">Open</a> [...] <main> <router-outlet name="content"><router-outlet> </main> [...] app.compoment.html <router-outlet><router-outlet> app.routing.modu ...

Angular's ng-model is unable to access the value of an object array

When selecting the days, users should be able to input check-in and check-out time ranges dynamically. However, there seems to be an issue with retrieving the values and data format. The ng model is unable to capture the check-in and check-out values. The ...

Determining the appropriate generic type in Typescript

In my code, there is a method designed to extend an existing key-value map with objects of the same type. This can be useful when working with database query results. export function extendWith< T extends { id: string | number }, O = | (T[" ...