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

Advanced type generics in Typescript

I've hit a roadblock in my attempt to ensure type safety for a function that should take an object and return a number. Despite numerous efforts, I haven't been successful. To give you a simple example (the actual application involves more comple ...

Issue with deploying meteor application using fibers

I am trying to run a Meteor v1.6.1 app on Ubuntu 17.10. MongoDB: mongodb-win32-x86_64-2008plus-ssl-3.6.3 NodeJS: node-v8.10.0-x64 The error message I encountered during the build process is as follows: What steps should I take to resolve this issue? ...

When running `ng serve` or `ng build --prod`, the dist folder is not created in an Angular 4 application

I recently completed building an Angular 4 app using angular-cli version 1.0.4 and generated the production build with the command ng build --prod. However, I encountered a problem as the expected dist folder was not created after executing this command. ...

The query in the Mongo shell is not functioning as expected when used with mongoose

I have crafted a shell query that functions flawlessly when executed on mongo shell, but does not yield any results when run using mongoose in nodejs + typescript; Mongo shell db.userworks.aggregate([ { $match: { user: ObjectId("6 ...

Using TypeScript: Defining function overloads with a choice of either a string or a custom object as argument

I'm attempting to implement function overloading in TypeScript. Below is the code snippet I have: /** * Returns a 400 Bad Request error. * * @returns A response with the 400 status code and a message. */ export function badRequest(): TypedRespons ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

Encountered difficulty retrieving properties from the req.query object within expressjs

My setup includes a router configuration like this: router.get('/top-5-cheap', aliasTopTours, getAllTours); I've also implemented some middlewares: Middleware aliasTopTours: In this middleware, I am setting certain properties on the reque ...

`Is there a way to manage date formats across all components using a single method in Angular?`

I need assistance with controlling the date format of dates displayed in different components using one typescript file. How can I achieve this? app.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', ...

Merging RXJS observable outputs into a single result

In my database, I have two nodes set up: users: {user1: {uid: 'user1', name: "John"}, user2: {uid: 'user2', name: "Mario"}} homework: {user1: {homeworkAnswer: "Sample answer"}} Some users may or may not have homework assigned to them. ...

Is it possible to utilize an enum for typing an array variable?

Is there a way to use an enum to define the valid types that an array can contain? I have been unable to find a solution so far, and I am curious if it is feasible. Below is the example code I have tried: interface User { name: string; } interface Ad ...

Ensure that the database is properly configured before running any test suites

Currently, I am facing the challenge of seeding my database with all the necessary resources required to successfully test my API. These tests are spread across multiple files. Is there a method that will allow me to fully seed the database before any tes ...

Troubleshooting problem with rxjs subscription impacting component UI refresh

Currently, I am diving deep into the world of rxjs Observables, Observers, and Subscriptions. In order to grasp their functionality better, I decided to experiment with a sample code that updates the UI with random numbers at intervals of 1 second. My ulti ...

What is the best method for extracting embedded documents from a MongoDb database?

I'm facing an issue with a dictionary of embedded documents and I need to remove all embedded documents from the dictionary where the key is not abc. The mongo script I have been using successfully is as follows: db.getCollection("users").update( ...

Issue with saving date values accurately in Nestjs/Prisma

After logging the response body before saving it to the database, I noticed that the shape is correct. Here's what it looks like: //console.log response body CreateOpenHourDto { day: 'WEDNESDAY', startTime: 1663858800000, endTime: 16638786 ...

Leveraging mongo's updateZoneKeyRange function to optimize zone ranges

How can I update the range of an existing zone named hot from { "id" : 1507520572 }, { "id" : { "$maxKey" : 1 } using the command sh.updateZoneKeyRange('db.collection', { id: 1507520572 }, { id: 9999999999 }, &apo ...

TypeScript mandates the inclusion of either one parameter or the other, without the possibility of having neither

Consider the following type: export interface Opts { paths?: string | Array<string>, path?: string | Array<string> } The requirement is that the user must provide either 'paths' or 'path', but it is not mandatory to pa ...

Expanding on the nested document in mongoose

I have been working on setting up a nested mongoose document configuration in the following manner: models/data.js var mongoose = require('mongoose'); var addresses = new mongoose.Schema({ "street": String, "city": String, "state": Stri ...

How to Unsubscribe from an Angular 2 Subscription Automatically After a Timeout

I am looking for a way to disregard the response from my API in case it takes too long to fetch. Currently, I am using this.http.get(mysqlUrl).subscribe() to retrieve the response. However, I would like to terminate that subscription if it exceeds a dur ...

Having difficulties in TypeScript identifying types within a project containing multiple node_modules directories

I am currently in the process of transitioning a codebase from Flow to TypeScript. I am encountering an issue with the error message Cannot find module 'SOME DEPENDENCY' or its corresponding type declarations.ts(2307) for several dependencies tha ...

What's the best way to insert values into data binding within a Typescript/ Angular mat Table?

Objective: Create a dynamic table using JSON data <mat-table class="mat-elevation-z8" *ngIf="carrierRates" [dataSource]="carrierRates"> <ng-container *ngFor="let columnName of columnsList" matColumn ...