Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda