Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

466
Views
How to update Data in MongoDB when checked body is selected

How can I update data in MongoDB when I check the checkbox without submitting any form.

My Schema

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,
            },
        },
    ],
});

I want to update the done element which is in todos array.

I tried to do this.

Main Client Side 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 },
            });
        }
    });
});

In the front-end I have set the value of the checkbox to the _id of the object.

/routes/index.js here I am handling my routes

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

And Finally I am handling that contorller in my 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);
    }
};

But I am not getting any user in my console.

Please tell me where I am wrong.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You don't need to use aggregate. You can do it by using $elemMatch

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

For more information read the docs

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!