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

134
Views
Is there a way to code dynamic keys in findOneAndUpdates with mongoose?

I have 5 buttons with different IDs and depending on which ID the buttons have, I save content in the database. I think my solution is not implemented very nicely but i also don’t know how I could do it better, because for example template literals in object keys do not work.

if (button.id === 'song1') {
    await model.findOneAndUpdate(
        {
            userId: user.id,
        },
        {
            'song1.name': songName,
            'song1.link': songLink,
        }
    );
} else if (button.id === 'song2') {
    await model.findOneAndUpdate(
        {
            userId: user.id,
        },
        {
            'song2.name': songName,
            'song2.link': songLink,
        }
    );
} else if (button.id === 'song3') {
    await model.findOneAndUpdate(
        {
            userId: user.id,
        },
        {
            'song3.name': songName,
            'song3.link': songLink,
        }
    );
} else if (button.id === 'song4') {
    await model.findOneAndUpdate(
        {
            userId: user.id,
        },
        {
            'song4.name': songName,
            'song4.link': songLink,
        }
    );
} else if (button.id === 'song5') {
    await model.findOneAndUpdate(
        {
            userId: user.id,
        },
        {
            'song5.name': songName,
            'song5.link': songLink,
        }
    );
}

Any Ideas to code that better?

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

0

This could lead to an opinion based answer, so this post might get closed, but to answer your question regarding string literals in object property names, you could maybe create the update object using bracket notation? ie.

update_info = {};

update_info[button.id + '.name'] = songName 
update_info[button.id + '.link'] = songLink 

await model.findOneAndUpdate(
        {
            userId: user.id,
        },
        update_info
    );

This would make the code more dynamic.

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!