Avoiding the creation of fields that have not been inputted in TypeGraphQL

@Resolver()
export class NameCardCreateResolver {
  @Mutation(() => BaseMutationResponse)
  async namecardCreate(
    @Arg("chosenSNSUrls", () => SNSInput)
    { facebook, twitter, instagram, blog, youtube }: SNSInput,
    @Arg("owner", () => NameCardOwner)
    { ownerEmail }: NameCardOwner
  ): Promise<BaseMutationResponse> {
    const response = new BaseMutationResponse();
    try {
      await NameCardModel.create({
        sns: {
          facebook,
          twitter,
          instagram,
          blog,
          youtube
        },
        owner: {
          email: ownerEmail,
        },

and also defined the SNSINPUT type as shown below:

@InputType()
export class SNSInput {
  @Field({ nullable: true, defaultValue: null })
  facebook?: string;

  @Field({ nullable: true, defaultValue: null })
  instagram?: string;

  @Field({ nullable: true, defaultValue: null })
  youtube?: string;

  @Field({ nullable: true, defaultValue: null })
  blog?: string;

  @Field({ nullable: true, defaultValue: null })
  twitter?: string;
}

although it works well, I noticed that in my MongoDB field, unnecessary null values are still being created.

View image description here

How can I prevent these unnecessary null processed sns fields from being created?

Answer №1

To exclude a field from MongoDB, simply assign the value undefined instead of null. This will prevent the field from being included in the document.

If your typegraphql annotation includes defaultValue: null, consider removing it as this may default the field to null.

@InputType()
export class SNSInput {
  @Field({ nullable: true })
  facebook?: string;

  @Field({ nullable: true })
  instagram?: string;

  @Field({ nullable: true })
  youtube?: string;

  @Field({ nullable: true })
  blog?: string;

  @Field({ nullable: true })
  twitter?: string;
}

Alternatively, if you wish to retain null values in your input, you must explicitly replace them with undefined or delete them using delete.

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

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. https://i.sstatic.net/MtO8l.png In contrast, highlighted near the red arrows i ...

A function in Typescript that can handle dynamic keys and values using generics

function convertArrayToObject<T>(array: T[], key: keyof T): Record<string, T> { return array.reduce( (accumulator: Record<string, T>, currentValue: T) => Object.assign(accumulator, { [String(currentValue[key])]: cur ...

What is the best way to define a category in order to utilize a saved string as a variable for referencing it?

An object named CONFIG holds the following information: export const CONFIG = { buttonDestinations: { detailedStats: `detailedStats`, mealPlans: `mealPlans`, products: `products` }, buttonTexts: { detailedStats: ...

Angular 4 HTTP Requests Failing to Retrieve JSON Data

I am currently working with the following method in my Typescript: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const params: string = [ `onlyActive=${onlyActive}`, `page=${page}` ].join('&&apo ...

Creating an Express server using Webpack, TypeScript, and ESM

Hello, I am currently working on a small project using node.js and TypeScript with webpack. Here is a snippet of my tsconfig.json file: tsconfig.json { "compilerOptions": { "lib": ["ESNext"], "target": "ES2020", "module": "NodeNext", "mod ...

Typescript: defining an interface that inherits properties from a JSON type

When working with TypeScript, I've utilized a generic JSON type as suggested in this source: type JSONValue = | string | number | boolean | null | JSONValue[] | {[key: string]: JSONValue} My goal is to cast interface types matching JSON to and ...

Creating applications locally with express, mongodb, and mongoose

Currently, I'm developing an application with express, mongodb, and mongoose. I am experiencing issues when trying to run the app on my local machine without internet connection because it is unable to connect to the mongodb server. I assumed that if ...

What is the most effective method for managing locale translations in a web application while also considering offline functionality?

Tech Stack: Nuxt.js with @nuxtjs/i18n, Express, Mongoose/MongoDB Keep in mind that the web application should support offline mode, requiring content and translations to be downloaded or included in the app package for multiple languages. General purpose ...

The process of importing mongoose models is not functioning properly

Initially, I had no issues when defining my schema and models in the same file where they were being used. However, when I tried to import them following the examples I found online like this... index.js var mongoose = require('mongoose'); var ...

Having trouble locating the custom interface name in a TypeScript custom npm package?

I have an Angular application in TypeScript that is built with webpack. I also have an npm package (hosted in Sinopia, not on npm) structured as follows: my-custom-npm-package - index.ts - studentStorage.ts - student.d.ts student.d.ts interface IStudent ...

Implementing a new archival capability on my website

I'm implementing a feature on my website that allows users to archive posts as needed. The site is developed using MERN stack and a RESTful API. Initially, I considered updating the Post model with an 'archived' property like: { archived: ...

Alert: There are unresolved parameters for Storage in the file located at PATH/node_modules/@ionic/storage/es2015/storage.d.ts

Important Notice: Caution: Cannot resolve all parameters for Storage in /Users/zzm/Desktop/minan/node_modules/@ionic/storage/es2015/storage.d.ts: (?). This will become an error in Angular v5.x I have followed the instructions in this answer but the ...

Include the designated return type within a fat arrow function

No matter how hard I look, I cannot figure out the correct way to combine return type annotation with fat arrow syntax. class BasicCalculator{ value:number; constructor(value:number=0){ this.value=value; } add= (operand:number)=> ...

The Django webpack loader for vuejs+typescript encountered an error and refused to run the script from due to its incompatible MIME type of 'text/html'

I'm currently utilizing Django as the backend and Vue3 as the frontend for my application. While I didn't encounter any issues on the development server, I'm facing problems with page rendering in production. Despite closely following all th ...

ServiceAccountKey cannot be located by Firebase deploy

I am in the process of integrating a serviceAccountKey into my Typescript cloud functions project. var serviceAccount = require("/Users/kareldebedts/myAppName/functions/serviceAccountKeyName.json"); admin.initializeApp({ storageBucket: "appName.appspot ...

Updating Arrays Conditionally and Adding New Elements in a MongoDB Document Using C#

When looking at the given document structure: public class Disclaimer { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public ObjectId Id { get; set; } public List<Override> Overrides { get; set; } } public class Override { p ...

Modifying an element's value according to user input: Step-by-step guide

Within my dropdown menu, there is a single option labeled "Others". Upon selecting this option, a textbox appears allowing me to input custom text. Is it possible to dynamically update the value of the <option value="Others">Others</option>, ...

Locating a file, transforming it into a tangible entity, and associating it with a specific identifier in Mongoose

Situation: In my mongo database, I have a collection named collection within the database test. There exists only one document in test.collection: { "_id" : ObjectId("64e4a6f9d1d7ba45250dc2c1"), "key" : "value"} Inquiry: With Mongoose, how can I retrieve ...

Looping to run an async process (sequilize.authenticate) multiple times until successful

I need my microservice to wait for the database to become available before proceeding. There is a sidecar Cloud SQL proxy involved that requires some time for the database connection. My current approach involves a for loop that retries connecting after a ...

Do MongoDB documents maintain the order of arrays?

Despite my efforts, I haven't been able to find concrete confirmation in MongoDB documentation that arrays within documents are maintained in the order they were inserted or updated. Allow me to pose the seemingly simple question: does MongoDB preser ...