Using NestJS and Mongoose to create a schema with a personalized TypeScript type

I'm struggling to devise a Mongo Schema using nestjs/mongoose decorators based on the structure of the class below:

@Schema()
export class Constraint {
  @Prop()
  reason: string;

  @Prop()
  status: Status;

  @Prop()
  time: number;
}

The challenge lies in the definition of Status, which looks like this:

export type Status = boolean | 'pending';

I'm having difficulty determining what to pass to the prop decorator for the status attribute, as I keep encountering the following error message:

Error: Cannot determine a type for the "Constraint.status" field (union/intersection/ambiguous type was used). Make sure your property is decorated with a "@Prop({ type: TYPE_HERE })" decorator

Using { type: Status } doesn't resolve the issue because Status is a type, not a Class.

Answer №1

Dealing with a similar issue led me to the solution provided by @sven-stam on how to implement Mixed type in this context. Here is how I integrated it:


import { Prop, Schema } from '@nestjs/mongoose';
import mongoose, {
  HydratedDocument,
  Schema as MongooseSchema,
} from 'mongoose';

export type UserDocument = HydratedDocument<User>;

@Schema()
class User {
  @Prop()
  username: string

  @Prop({default: false, type: MongooseSchema.Types.Mixed })
  paid: boolean | 'waiting'
}

Answer №2

If the variable status can take on either boolean or string values, that indicates it is a mixed type. In this case, consider adjusting your data type to Mixed Data Types

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

Tips for extracting certain keys from an interface using template string types?

I am dealing with a code snippet here that accepts a string array named possibleColumns for a specific database table. It then takes the incoming source and attempts to find a column containing {source}_id. For example, if the possibleColumns includes [&q ...

Satisfy TypeScript by accommodating both array and non-array values within a single variable

I am looking to implement an array of Payments for each Rent instance, but I also want the flexibility to pass either a single Payment object or an array of Payment objects through the constructor... However, the issue arises when I try to assign this.pay ...

Is there a way to dynamically arrange users based on their proximity to the current user in Meteor?

Struggling with the complexities of sorting data reactively in a Meteor application has been a recurring challenge for me. Despite countless attempts, I have never come across a satisfactory solution to achieve the desired outcome. Each time, I reluctantly ...

The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks const firstUser = await connection .getRepository(User) .createQueryBuilder("user") .where(`user.id = '${id}'`) .getOne(); However, in the typeorm documentatio ...

Angular 2 Animations are currently malfunctioning

After following the Angular 2 Documentation for Animations (link to https://angular.io/docs/ts/latest/guide/animations.html), I successfully migrated my project to Angular 4.0.1. Below is a snippet from my package.json: "@angular/common": "~4.0.1", "@angu ...

Eliminate repeating elements in an array of objects with multiple levels

I'm facing a challenge with filtering an array of objects based on the condition that myDatas.items.flaggedItem should not be null, while also eliminating duplicates where myDatas.items.id are identical. This scenario should result in only 2 items bei ...

Simultaneously Accessing Data from MongoDB and MySQL

I have been working on retrieving data from my MongoDB database, which contains chat conversations. The retrieval process is successful and I am getting the desired output. However, in my MongoDB database, I only store userIDs, so I need to fetch additiona ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

When implementing setInterval in React with TypeScript, remember to utilize the useRef hook

In my next.js app, I am implementing a basic animation. let flipInterval = useRef(); const startAnimation = () => { flipInterval.current = setInterval(() => { setIsFlipping((prevFlipping) => !prevFlipping); }, 10000); }; When tryin ...

Issue with the loading of Firebase in Chrome extension's background script is inconsistent

I am currently working on developing a Chrome extension that utilizes Google Firebase for authentication. In my project, I am employing webpack for building purposes, with Firebase being utilized in the background script. However, during the initial initi ...

Tips for converting TypeScript phrases in an Angular 2 application

When it comes to Angular 2 i18n, there are two main platforms that come to mind: The official method, and ng2-translate. Personally, I lean towards following the recommendations in the official documentation. The process of translating HTML strings seems s ...

No default export function available on this page

Recently delving into Nextjs, I'm currently in the process of setting up a MongoDB connection using middleware configuration. Let me showcase my code: import type { NextApiRequest, NextApiResponse } from 'next' import { connectMongoDB } fro ...

Firebase Promise not running as expected

Here is a method that I am having trouble with: async signinUser(email: string, password: string) { return firebase.auth().signInWithEmailAndPassword(email, password) .then( response => { console.log(response); ...

Unable to make changes to a document

Currently encountering issues while attempting to update a document with a simple command, but the changes are not being saved. Seeking advice on how to troubleshoot this. Here is the query: db.Customers_DEV.update( {"fn": "QA_Isabel10K"}, { $set: { ...

Leverage TypeScript for modifying local node package alterations

As a newcomer to npm and TypeScript, I may be overlooking something obvious. Our team has developed a node package in TypeScript for internal use, resulting in the following file structure: src/myModule.ts myModule.ts The contents of myModule.ts are as f ...

Is there a way to specifically execute a Mongoose validate function solely for the create user page and not the edit user page?

Exploring Different Tools In the process of developing a website using Node.js, Express, and MongoDB. Leveraging mongoose for interacting with the MongoDB server has been quite beneficial. However, I encountered an issue where a function within my Mongo ...

Using TypeScript with ReactJS

While working on a form using React-select, I encountered an issue when trying to pass parameters to a function. The error message returned was: Expected 1 arguments, but got 0.ts(2554) index.tsx(31, 31): An argument for 'selectRef' was not pr ...

There was a unique key error in the "products" collection of the database. The index "product_id_1" had a duplicate key with a value of

Seeking assistance urgently! I've been facing a blockage for the past two days in retrieving all my products. An error involving duplicate keys is hindering the GET action. Despite attempting various methods such as remove({}), deleteMany({}), or comb ...

The MongoDB insert operation in C# is significantly slower than the SQL Server insert operation, taking 1000 times longer

Utilizing a file structure, I am extracting and inserting data as depicted in the image below. Folder-->sub-folder-->sub-folder-->file Prior to this, the data was stored in SQL Server. The process of transferring all data to SQL took 26 seconds, ...

I encountered TS2300 error stating a duplicate identifier appeared once I transferred my code to Angular CLI

Currently undergoing the process of transitioning our code to Angular CLI for our hybrid app. The plan is to migrate the Angular part to CLI while the AngularJS portion continues to be handled by custom Webpack. It's worth noting that both parts (Angu ...