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

216
Views
Setting value via dynamically generated key in then-block of a returned findOne() promise in Mongoose Node.js

I would like to write a function that can be called whenever I set a default value in my Schema.

At the moment I keep repeating the same code as default value (getting the default SVG from its collection) for each of my parts (e.g. body, ear, head, arm) - which works and looks like this:

arm: { type: partSchema, default: function (){

  Arm.findOne({ name: 'default' })
  .then(pic => {
    this.model.arm = pic;        

    Pattern.findOne({ name: 'default' })
    .then(pic => {
      this.model.arm.pattern = pic;
    })
    .catch(err => {
      console.log(err);
    });
    
  })
  .catch(err => {
    console.log(err);
  });
  

What I would like to do is something like this:

function defaultPart(user, part) {

  //will turn e.g. part='arm' to 'Arm' so my function can find the apropriate model
  var PartModel = mongoose.model(`${part.charAt(0).toUpperCase() + part.slice(1)}`);

  PartModel.findOne({ name: 'default' })
    .then(pic => {
      //model.part does not exist and will not be filled with data, logically
      //I'd instead like the function to exchange part with 'arm'
      this.model.part = pic;

      Pattern.findOne({ name: 'default' })
        .then(pic => {
          //same concept as above
          this.model.part.pattern = pic;
        })
        .catch(err => {
          console.log(err);
        });

    })
    .catch(err => {
      console.log(err);
    });

}

and then call it within my Schema

arm: {
  type: partSchema, default: function () {

    defaultPart(user, 'arm');

  }},

I've tried to look for answers within Stackoverflow, but the answers mostly revolve around dynamically creating queries like these:

Is there a way to use a variable for the field name in a find() in mongoose?

However I'm not interested in querying my DB, I want to set values within, or rather assign their keys dynamically. I feel like I'm missing something very basic here, something like a template string in Javascript, but I just can't figure out what it is.

Is my idea feasable or will I be stuck with copy-pasting it to all my Schemas (total: 15) separatly?

about 4 years ago · Juan Pablo Isaza
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!