Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda