Implement a query in Mongoose using the Schema First methodology within NestJS

In the beginning, I must mention that this query bears resemblance to this one which points to this particular question. My inquiry mirrors the second link with a noticeable distinction. I am endeavoring to expand a class produced by NestJS which delineates a property.

I'm employing NestJs in conjunction with the Schema-first technique detailed here. Furthermore, I am producing a file of classes based on my GraphQL Schema.

This is the Schema:

type Location {
  name: String!
  owner: User!
}

This generates the class:

export class Location {
    name: string;
    owner: User;
}

My aim now is to extend this class so that I avoid repetitiveness (bearing in mind there are numerous fields not displayed). Additionally, I intend to incorporate fields residing within a document but not present in the schema (like _id in this instance). Below lies my LocationDocument along with my schema.

export interface LocationDocument extends Location, Document {
  _id: Types.ObjectId
}

export const LocationSchema: Schema = new Schema(
  {
    name: {
      type: String,
      required: true,
    },
    owner: {
      type: Types.ObjectId,
      ref: 'User',
    }
);

The predicament arises now. The auto-generated Location class from the GraphQL schema defines the owner property as a User type. However, in actuality, it is merely a mongodb id until populated by Mongoose. Therefore, it can be either a Types.ObjectId or a User inside a UserDocument. Attempting to define it as follows results in an error:

export interface LocationDocument extends Location, Document {
  _id: Types.ObjectId
  owner: User | Types.ObjectId;
}

This triggers a compiler error stating that LocationDocument wrongly extends Location. This outcome is understandable. Is there any feasible method to broaden the User Class yet stipulate that the owner property may be either a User Type (post Mongoose population) or a mongo object ID (as preserved in the database)?

Answer №1

After much consideration, I came to the conclusion that having a property that can serve as two types may be convenient with Mongoose and JS, but it lacks a clear type definition. Within my schema, I specified an owner field of User type. However, in the database and corresponding document, I opted for an OwnerId instead. This design allows API users to interact without needing to worry about the ownerId for establishing relationships. On the other hand, within my resolver function, I handle the relationship using Id - one being a Mongo ID type and the other being a User type.

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

Modify the color of an Ionic button for a single button, rather than changing the color for all buttons

How can I modify this code so that only the clicked button changes its color, not all of them? Here is the current code: .html: <ion-col size="6" *ngFor="let data of dataArray" > <ion-card> <ion-card-header> ...

Utilizing Mongoose populate to automatically include default selected fields in virtual references

In my mongoose schema, I have defined a virtual like this: PostSchema.virtual("author", { ref: "User", localField: "userId", foreignField: "_id", justOne : true, }); When using .find(), I can populat ...

Encountering difficulties while attempting to deploy image on kubernetes due to issues with packaging structure

After successfully building with the dockerfile provided below, I encountered an issue when trying to deploy my application on EKS. FROM node:12 # Create app directory WORKDIR /usr/src/app COPY udagram-feed/package*.json ./ RUN npm ci # Bundle app sou ...

ESLint does not recognize the types from `@vuelidate/core` when importing them

When working with TypeScript, the following import statement is valid: import { Validation, ValidatorFn } from '@vuelidate/core' However, this code triggers an error in ESLint: The message "ValidatorFn not found in '@vuelidate/core' ...

Leveraging the ngFor local variable within nested elements

Is there a way to properly display a property of the local variable theme, such as theme.name? Below is an example of how my *ngFor is structured: <ul> <li *ngFor="#theme of themes"> <span>theme.name</span> </li> ...

Searching for a specific document using AngularFirestore - what's the best method?

Is it possible to create an Observable that is limited to a single document? While the code provided creates an Observable for querying multiple documents: foo.component.ts import { AngularFirestore } from '@angular/fire/firestore'; import { O ...

Do Prisma Migrations Require a Default Value?

I'm struggling with Prisma data modeling and have tried almost everything to resolve an error I keep getting. The error states that the table needs a default value even though I have already assigned it an ID. I attempted to remove the relation name, ...

Is there a glitch in the angular binding mechanism?

I am working with a component that includes a select option and a text input field. The purpose of the "select" is to choose a description of an object, while the input field is used to specify the quantity assigned to the selected object. In my form, I ne ...

What is the reason that I am able to form an object using string literals, but introducing generics complicates the process?

My goal is to create an Object using string literals. export type MyCustomType<T extends string> = { propertyFromCustomType: T; }; export type CustomTypeWithLiteral<T extends string> = { [P in `${T}_with_literal`]: number; }; When my cre ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...

The ng2-chart library displays date in the form of a Unix timestamp

I have a date object imported from my database, but it is showing up as a Unix timestamp (-62101391858000). I know I can format the date using pipes like {{myDate | date:medium}}, however, I am using ng2-charts so I need to find a different solution. My ch ...

React blogging site's administrative dashboard

https://i.sstatic.net/M6fUJ.png I am currently in the process of developing a blogging platform using MERN technology. Specifically, I am focused on creating a restful API with Node.js, Express, and MongoDB. The frontend, built with React, consists of thr ...

Error: Property 'instance' is undefined and cannot be read

Trying to confirm the functionality of the following method: showSnackbar(): void { if (this.modifiedReferences.length) { const snackbar = this.snackbarService.open({ message: '', type: 'success', durat ...

Utilizing MongoDb and Node.js for efficient data input

I am currently facing an issue while trying to input data into a mongodb collection using node.js. I believe I have the necessary access to the collection in question. var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitt ...

The Mongodb update feature will only execute successfully when the .then() method is included in the

My goal is to increment a field in mongodb each time a request is made. The update function seems to only work properly when I include .then() after the function call, but I'm not sure why this is necessary. While the code is functional, I am curious ...

Confusion arises from the error message 'No overload matches this call'

Currently, I am working on a weather application using Angular based on the concepts from the book Angular for Enterprise-Ready Web Applications - Second Edition. I am in the process of adding a search component to the app, which will allow users to displa ...

The Array of Objects is not being generated from Action and Effects

I'm attempting to retrieve an array of objects stored in the User model. I've created both an Action and an Effect for this purpose. The structure of the User Model is as follows: export interface User { _id: string, firstName: string, lastName: ...

limitation on pairings of two generic types

How can I specify in TypeScript that "You can pass in any two objects, as long as their combination satisfies type X"? For example, consider the following function: function myFunction(options: {x: number, y: string}){ } Now, let's say we have anot ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

Looking for assistance! Seeking the most optimal method to launch a MERN ecommerce platform for production

After completing the development of a multivendor ecommerce web application using the MERN stack, I am now faced with the task of deploying it on Digital Ocean. I am seeking advice on whether to deploy directly on Digital Ocean using Nginx firewall or opt ...