Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

95
Views
How to set a property value based on other property in Mongoose

I have the following schema as exemple:

const categorySchema = new mongoose.Schema({
  categoryId: {type: Number},
  title: {type: String, default: "standard"},
})

I want that the category with categoryId equal 1, must always be "standard", and if the title is not specified, it will assign the categoryId = 1. Is there any way to do that in Mongoose?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Ok so we have two cases here:

  1. category with categoryId equal 1, must always be "standard"

You could use a pre hook, the code would be like this:

  const categorySchema = new mongoose.Schema({
    categoryId: {type: Number},
    title: {type: String, default: "standard"},
  })

  categorySchema.pre('save', function (){
    if(this.categoryId === 1){
      this.title = "standard";
    }
  })

  const categoryModel =  mongoose.model('Category', categorySchema);
  const category = new categoryModel({title: 'Greaat', categoryId: 1});
  await category.save();
  1. if the title is not specified, it will assign the categoryId = 1

With your current code it shouldn't work because you're indicating with default: "standard" that if a title is not specified you have to assign standard as default, so you should leave the default property and manage it in the pre hook to achieve that but that logic seems to me complicated maybe you need to think a little bit better what is the problem, because this kind of solutions are overcomplicated IMHO

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!