How to update mongodb document with only checked checkbox data


If I have data that looks like this:

    username: "tester"
        _id: 60e430d45395d73bf41c7be8
        exercise: "a"
        _id: 60e4329592e3fa445836d983
        exercise: "b"
    exercise: "c"

What would be the best way to push data from a checkbox form? This is what I have so far:'/routines/:username/:day', async (req, res) =>{ //add exercise from add page
    let day =
    await Routine.updateOne( {routineUsername: req.user.username}, { $push: { [day]: {$each: [
        {exercise: req.body.a}, {exercise: req.body.b}, {exercise: req.body.c}, {exercise: req.body.d}, 
    ]} } } )
    req.flash('success_msg', 'Exercise added to routine!')

And this will update the document but if you only check one checkbox, the other one will be stored as an empty object. What’s the solution to this?


Since you only have specific checkboxes. What you can do is create an update payload first by checking if a checkbox is applied and only push that one in array.

// destruct day
const { day } = req.params;

// create an empty payload
const updatePayload = { [day]: [] };

// now check your specific checkboxes 
if (req.body.a) {
   updatePayload[day].push({ exercise: req.body.a });

// and so on

// now finally update
await Routine.updateOne( {routineUsername: req.user.username}, updatePayload);

Now, one thing here is that, I replace the current array with new ones so the previous check boxes that were ticked are removed and automatically not checked. So every time you’ll have to push all the ticked boxes.

A better way to handle checkboxes would be to change your current strategy and push an array of checkboxes from your frontend for a specific day. Store all your checkboxes in db and maintain a key like isChecked to check if checkbox is ticked or not. Then you can replace the array completely.

Something like this:

// destruct day and checkboxes
const { day, checkboxes } = req.params;

// and simply push
await Routine.updateOne( {routineUsername: req.user.username}, 
        { [day]: checkboxes });

Again there could be numerous other ways to achieve this as well.

Answered By – Ali Hussam

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published