简体   繁体   English

如何仅使用选中的复选框数据更新 mongodb 文档

[英]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.将所有复选框存储在 db 中并维护一个键,如isChecked以检查复选框是否被勾选。 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.同样,也可以有许多其他方法来实现这一目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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