Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug while creating document #14413

Closed
2 tasks done
gioimtg2003 opened this issue Mar 4, 2024 · 4 comments
Closed
2 tasks done

Bug while creating document #14413

gioimtg2003 opened this issue Mar 4, 2024 · 4 comments

Comments

@gioimtg2003
Copy link

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.0.3

Node.js version

v21.5.0

MongoDB server version

7.05

Typescript version (if applicable)

No response

Description

I tried to create document but it gave error Error - ValidationError: Description: Path Description is required

Steps to Reproduce

Model

let Order = new mongoose.Schema({
  Description: {
        type: String,
        required: true
    },
};
let data = {Description : description ?? ""}; 
let order = new SchemaOrder(data);
//error
let newOrder = await order.save();

Expected Behavior

No response

@sean-daley
Copy link

I’m guessing it’s because your document is passing in an empty string for description. A required string means it has a value (and the empty string is not considered a value). You have a few options I think including.

  1. https://mongoosejs.com/docs/api/schematype.html#SchemaType.checkRequired() (You can change the behavior of that check globally)
  2. What we’ve done at my company for these is make it not required and put in a default of ‘’ in th schema so that it always gets a value.

probably other solutions too but those are the two main ones I know about.

@FaizBShah
Copy link
Contributor

I agree with @sean-daley . I guess what you're looking for is default: "" instead of required: true

@donoftime2018
Copy link

My question is. In the line let data = {Description : description ?? ""}; , where does the identifier 'description.' Moreover, you haven't declared any path in the schema called 'description.'

@vkarpov15
Copy link
Collaborator

Empty string "" fails the required check for strings in Mongoose by default. If you want to allow empty strings to pass required validator for strings, run the following code when your program starts.

// Allow empty strings to pass `required` check
mongoose.Schema.Types.String.checkRequired(v => v != null);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants