Could a shortcut for quickly converting a deconstructed Mongo response to DTO be available?

Suppose I have a mongoDB table with five properties, but I only need to retrieve four of them excluding any additional mongo-specific information like v1. In this case, I can easily map the response to a dto as shown below:

const product = await this.productModel.findById(productId).exec()
return { id: product.id, title: product.title }

Is there a shortcut or quick way to destructure the return statement in order to extract all fields from an interface (Product) directly from the product response? This would be convenient especially when dealing with a large number of properties, such as 127 out of 140 entries.

interface Product {
   id: string
   title: string
   ...
}

Answer №1

Regrettably, TypeScript interfaces do not physically exist once your program is compiled

An interface serves as a blueprint that outlines the requirements within your application. It sets the guidelines for classes to adhere to. Any classes derived from an interface must adhere to the established structure.

When compiling TypeScript code, interfaces are not directly converted into JavaScript. Instead, they are utilized for type checking purposes, often referred to as "duck typing" or "structural subtyping".

As a result, you cannot directly access interface properties and manipulate them (although using reflection might be a workaround, it's generally discouraged)

One approach is to explicitly specify which fields to include or exclude from your object

For instance, imagine having an object that follows this interface:

interface Foo {
    field1: string;
    field2: string;
    field3: string;
    .....
    field140: string;
}

In this scenario, you can define the properties to exclude (opting for exclusion when dealing with 127 out of the total 140 fields)


// Note that this isn't specific to mongoose implementation (if utilized), 
// but rather illustrates the concept 

const FIELDS_TO_EXCLUDE = ["field128", "field129", "field130", ..., "field140"];

productModel.toDTO(){
    const documentData = this;
    FIELDS_TO_EXCLUDE.forEach(x => delete documentData[x]);
    return documentData;
}

This way, upon calling the toDTO function, you have the flexibility to modify the object by excluding (or including) specific fields as needed

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

What is the best way to link together Angular observables?

In order for my component to make API requests, it needs to check if certain app preferences are set. Currently, I have implemented a method where the component's data is refreshed every 2 minutes using a timer: ngOnInit(): void { this.subscriptio ...

Find and replace problem with findOneReplace

I am looking to locate a specific document in my database and update it with a new name and key information. Below is the Schema I'm working with: const Schema = mongoose.Schema; const vampireSchema = new Schema({ name: { type: String, required: t ...

Steps to stop mat-spinner upon receiving Job Success/Failure Notification from the backend

I have a task that runs asynchronously and takes a long time to complete. When the task starts, I display a mat-spinner with a timeout set at 60000 milliseconds. However, we now have a notification service that provides updates on the job status. I would l ...

Tips on adding an item to the array field of a model in Mongoose

I have 2 collections like this: const vocaSchema = { word: String, type: String, meaning: String, sente: String, semean: String, sug: String }; const Voca = mongoose.model('Voca', vocaSchema); const setVocaSchema = { ...

Issue: Using the command 'typings search' successfully locates a package, however, when attempting to install it using 'typings install', the process fails

I am currently attempting to install the Google Auth2 typings using 'typings': > typings search gapi.auth2 This command returns: NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED gapi.auth2 d ...

Angular 5: Issue with Module Resolution: Unable to locate '@angular/forms/src/validators'

Struggling to develop a unique validator using a directive, but encountering the following error: ERROR in ./src/app/CustomValidators/white-space-validator.directive.ts Module not found: Error: Can't resolve '@angular/forms/src/validators' ...

The concept of HttpClient type safety appears to neglect the use of interfaces

TL;DR: A specific angular interface was linked to HttpClient.get() responses. The responses were transformed into a seemingly general object type. Even though attributes like id and title were not defined on the interface, they were still accessible in t ...

Tips for managing Vue component content prior to data being fully loaded

I'm currently integrating product category data from Prismic into my Nuxt project and seeking guidance on best practices. Specifically, I need clarity on managing the state when data is still being fetched and there's no content to display in the ...

Encountering a ClassCastException with Morphia

Attempting to retrieve a MongoDB collection and convert the records into javabeans using Morphia, however encountering a cast error when trying to retrieve the collection of objects (seen below in App code): Exception in thread "main" java.lang.ClassCastE ...

The Freemode feature in SwiperJS is not functioning properly when used with React TypeScript

Having a slight issue with SwiperJS. Using version 10.1.0 and the following code : import { Swiper, SwiperSlide } from "swiper/react"; import "swiper/css"; export default function Discover() { return ( <> ...

Expectation in Observable: Unable to provide data retrieval

In my Angular 7 and Typescript project, I am faced with the challenge of reading a json file from within a zip file. Although I am able to successfully display the correct json output on the console, I am struggling to return this json data from the functi ...

Is it possible to programmatically include a getter method to a class in JavaScript or TypeScript?

My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area. I am curious about dynamically adding a getter method to a Prototy ...

Converting MongoDB data into a JavaScript array object

Hey there! I'm currently diving into learning MongoDB and Node.js. I recently managed to retrieve all collections of an order successfully, and below is the output: The orders: { __v: 0, nonmeat: 'pineapple', meat: 'Bacon', ...

Experimenting with parallelism using TypeScript/JS

Currently, I am tackling a TS project that involves testing concurrent code and its interactions with a database, specifically focusing on idepotency. My goal is to ensure that multiple requests modifying the same resource will either apply changes correct ...

Tips on searching for an entry in a database with TypeScript union types when the type is either a string or an array of strings

When calling the sendEmail method, emails can be sent to either a single user or multiple users (with the variable type string | string[]). I'm trying to find a more efficient and cleaner way to distinguish between the two in order to search for them ...

Show a selection of assorted files stored in the database

router.get("/alw", function(req, res){ Product.find({"category": "alw"}, function(err, allProduct){ if (err){ console.log(err) } else { res.render("products/alw", {products ...

Having trouble importing React components from a different file?

Having trouble with React due to issues importing components from external files. import React from 'react'; import ReactDOM from 'react-dom'; import '../resources/styles.scss'; import WelcomeView from '../views/welcome/W ...

pay attention to fluctuations in the observable's value

I am currently working on utilizing Ionic's loadingcontroller alongside a firestore query. From my understanding, this query returns an observable and also monitors changes in the query's value. However, is there a way to determine within the fu ...

Obtain a zero total through MongoDB's aggregation feature

Can you assist me with aggregate functions in Mongo? Here is my current aggregation code: const likes = await this.aggregate([ { $match: { post: postId }, }, { $group: { _id: '$likeType', count: { $sum: 1 }, }, }, ...

Troubleshooting partial content error while streaming MP4 with GridFS, NodeJS, and React

I have been working on my streaming project for a while now and everything seems to be going well, except for the fact that I am encountering a 206 partial content error when streaming large MP4 files. After conducting extensive research, it appears to be ...