首页 > 解决方案 > 选择检查主体时如何更新 MongoDB 中的数据

问题描述

当我选中复选框而不提交任何表单时,如何更新 MongoDB 中的数据。

我的架构

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        trim: true,
    },
    todos: [
        {
            task: {
                type: String,
                trim: true,
                required: 'Please Enter your Task',
            },
            dueDate: {
                type: Date,
                default: new Date(+new Date() + 3 * 24 * 60 * 60 * 1000),
            },
            dueTime: String,
            done: {
                type: Boolean,
                default: false,
            },
        },
    ],
});

我想更新数组中的done元素todos

我试图做到这一点。

主客户端 JavaScript

$(document).ready(function () {
    $('.todo--checkbox').change(function () {
        let isChecked;
        if (this.checked) {
            isChecked = true;
            $.ajax({
                url: '/todo/' + this.value,
                type: 'PUT',
                data: { done: true },
            });
        } else {
            isChecked = false;
            $.ajax({
                url: '/todo/' + this.value,
                type: 'PUT',
                data: { done: false },
            });
        }
    });
});

在前端,我已将复选框的值设置为_id对象的值。

/routes/index.js在这里我正在处理我的路线

router.put('/todo/:id', todoControllers.checkStatus);

最后我在我的todoCONtroller.js中处理那个控制器

exports.checkStatus = async (req, res) => {
    try {
        const user = await User.aggregate([
            { $unwind: '$todos' },
            { $match: { 'todos._id': req.params.id } },
        ]);

        // res.json(user);
        console.log(user);
    } catch (err) {
        console.log('error: ', err);
    }
};

user但是我的控制台中没有任何内容。

请告诉我哪里错了。

标签: javascriptnode.jsmongodbbackend

解决方案


您不需要使用聚合。您可以使用$elemMatch

const user = await User.find({
    todos: { $elemMatch: { _id: req.params.id } },
});

有关更多信息,请阅读文档


推荐阅读