Home > front end >  Is there a way to code dynamic keys in findOneAndUpdates with mongoose?
Is there a way to code dynamic keys in findOneAndUpdates with mongoose?

Time:10-22

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?

CodePudding user response:

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.

  • Related