Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

187
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda