简体   繁体   中英

How to update mongodb document with only checked checkbox data

If I have data that looks like this:

    _id:60e2edf7014df85fd8b6e073
    routineName:"test"
    username: "tester"
    monday:[{
        _id: 60e430d45395d73bf41c7be8
        exercise: "a"
    }{
        _id: 60e4329592e3fa445836d983
        exercise: "b"
}]
tuesday:[{
    _id:60e2ee8962c0c15840ecc69b
    exercise: "c"
}] 

What would be the best way to push data from a checkbox form? This is what I have so far:

router.post('/routines/:username/:day', async (req, res) =>{ //add exercise from add page
    let day = req.params.day
    try{
    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!')
    res.redirect('/')
    }
    catch(error){
        console.log(error)
    }   
})

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM