Function not functioning as expected in NestJS MongoDB unique field feature

I am trying to set the "unique:true" attribute for the name property in my NestJS - MongoDB schema, but it is not working as expected by default.

@Schema()
export class User {
  @Prop()
  userId:string;
  
  @Prop({ 
    type:String,
    required:true,
  })
  name:string;

  @Prop({ required: true})
  password:string;
  
  @Prop({ required: true })
  email:string;

  @Prop({default:"user"})
  role:string
}

This setup works fine for 'required' and 'default', however, the 'unique' field does not seem to be functioning properly.

Answer №1

To make the name property unique, include the `unique` attribute in the @Props decorator as shown below:

@Prop({ 
    type: String,
    required: true,
    unique: true
})
name: string;

Answer №2

Perhaps you intend to validate the input field by using the IsUnique method in this way:

import { Schema, Prop } from '@nestjs/mongoose';
import { IsUnique } from 'class-validator';


@Schema()
export class User {
  @Prop()
  userId:string;
  
  @Prop({ 
    type:String,
    required:true,
  })
  name:string;

  @Prop({ required: true})
  password:string;
  
  @Prop({ required: true })
  @IsUnique({ message: 'The field must be unique.' })
  email:string;

  @Prop({default:"user"})
  role:string
}

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

All components load successfully except for the worker in Webpack

I've been working on configuring webpack to bundle my react project. I successfully set up the webpack_public_path variable and all modules are loading correctly, except for the worker. const path = require('path'); const MonacoWebpackPlugi ...

I am faced with a challenge involving an asynchronous function and the best approach to executing it synchronously

I devised the following plan: // Primary Function to Follow // Capture necessary local data // Transform into required editable format // Iterate through user's local images // Append image names to converted d ...

Error in Typescript: Using forEach method - 'string' type cannot be assigned to 'never' type

I encountered an issue with this code where it's giving me an error message "Type 'string' is not assignable to type 'never'" at the specified comment. type serviceInfoType = { PORT: number; HOST: string; MS_NAME: strin ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

What is the best way to exhibit information from a get request within an option tag?

My GET request is fetching data from a REST API, and this is the response I receive: { "listCustomFields": [ { "configurationType": null, "errorDetails": null, "fieldId" ...

Modifying SASS variable within an Angular 2 TypeScript project

How can I update the Sass color variable based on user input in Angular 2? I came across a helpful resource, but it doesn't include any examples specifically for Angular 2. Any assistance would be greatly appreciated. Thank you! ...

Managing the state of dynamically generated tabs within a NextJS application

Looking to develop a web app in Next.js that includes tabs components. The goal is to manage various entities within each tab, such as utilizing a search bar to select different products. Upon selecting a product, a new tab will be generated with the produ ...

Retrieve all articles in groups of 10, ensuring that each article includes the necessary details of relevant users

In my project, I have set up two models named user and article. The data structure for each model is outlined below: const userSchema = Schema({ name: String, email: String, password: String }); const User = mongoose.model(‘user’, userSchema); mo ...

Searching for nested objects inside a MongoDB collection using Mongoose's find() method

Hey there! So I've got a Mongoose Schema that includes an object: const TrajesDeBano = new Schema({ modelo:{type:String, required: true}, tipo:{type:String, required:true}, talla:[{ s:{type:Number, required: true}, m:{type ...

Expanding upon React Abstract Component using Typescript

Currently, I am in the process of building a library that contains presentations using React. To ensure consistency and structure, each presentation component needs to have specific attributes set. This led me to create a TypeScript file that can be extend ...

What is the proper way to declare and utilize a constant list within a component template in NuxtJs?

Can someone help me with using itemList in a template? The itemlist is a static list, but I am unsure of where to declare it and how to export it to the template. <template> <table class="table table is-striped is-narrow is-fullwidth" ...

What is the best way to create a TypeScript type for React props that only allows prop B to be used if prop A is included in the component?

My component Text has 2 props: isHideable: boolean and hidden: boolean. How can I only allow Hidden as a prop when isHideable is set to true? Currently, both isHideable and hidden are being accepted which is not the desired behavior: type Props = { chi ...

An empty array is being returned from a mongoose function call

I'm currently working on a project that involves fetching random values from MongoDB using mongoose and storing them in an array. However, I am facing an issue where the array appears to be empty outside the function: exports.Run = (req, res) => { ...

What is the best way to destructure a blend of React props and my own custom props in my code?

I have a requirement to develop a custom React component that serves as a wrapper for the Route component in order to create secure routes. The challenge I am facing is how to access the element property, which is typically specified in the <Route> e ...

The error message "TypeScript is showing 'yield not assignable' error when using Apollo GraphQL with node-fetch

Currently, I am in the process of implementing schema stitching within a NodeJS/Apollo/GraphQL project that I am actively developing. The implementation is done using TypeScript. The code snippet is as follows: import { makeRemoteExecutableSchema, ...

Using Express to utilize MongoDB's Distinct and Find functionalities

My current project involves building an API, but I've hit a snag. I have multiple non-unique "Makes" in my "styles" collection and I need to filter them based on user input category (e.g. Sedan) to display only unique "Make" objects that match the cat ...

Encountering a Problem on Heroku: TypeScript Compilation Error with GraphQL Files - TS2307 Error: Module 'graphql' Not Found or Its Type Declarations Missing

While trying to compile my typescript project with graphql files for deployment on Heroku, I encountered the following error message: node_modules/@types/graphql-upload/index.d.ts(10,35): error TS2307: Cannot find module 'graphql' or its correspo ...

Can ng-content be utilized within the app-root component?

I have successfully developed an Angular application, and now I am looking to integrate it with a content management system that generates static pages. In order to achieve this, I need to utilize content projection from the main index.html file. The desi ...

Encountering the error message "TypeError: Cannot access property 'Token' of undefined" while compiling fm.liveswitch

The fm.liveswitch JavaScript Software Development Kit (SDK) is designed for use with both clients and your own backend "app server". It functions smoothly in the frontend thanks to webpack and babel. However, the same import statement: import liveswitch fr ...

Guide to Including an Object in AngularJS Scope

I am completely new to Angular JS and mongod. My goal is to add a new ingredient field to this page for the specific drink that the + button is clicked on. Here is how my view looks like: UI Image This is what my .jade file contains: block content ...