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

181
Vistas
How to update single value of document in Nodejs and mongo db

Hy, I'm new in nodeJS. I am stuck at updating a single entity of document. I'm updating the whole document easily but can't able to update a single value. code

router.patch("/:id", async (req, res) => {
  console.log(req.params.id);
  // check valid student
  let student = await Student.findById(req.params.id);
  if (!student) return res.status(400).send("Student Not Found");

  // validition
  // const { error } = validate(req.body);
  // if (error) return res.status(400).send(error.details[0].message);

  // update the student
  student = await Student.updateOne({_id:req.params.id},{$set: req.body});
  if(!student) return res.status(404).send('The student record not Updated')
  res.status(200).send('Student Record Updated')
});

Validation Function

function validateStudent(student){
    const schema = Joi.object({
        name:Joi.string().min(3).max(50).required(),
        fatherName:Joi.string().min(3).max(50).required(),
        email:Joi.string().min(5).max(50).required().email(),
        class:Joi.number().min(9).max(12).required(),
        fee:Joi.number().min(4000).max(10000).required(),
        address:Joi.string().min(1).max(255).required(),
        phone:Joi.string().min(1).max(255).required(),
    })
    return schema.validate(student)
}

Now It's updating my single value in DB but without validation, because if I uncomment the validation then it forces for all required field. How I can validate and update a single value which coming in API from the frontend?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

To update single field like email

student = await Student.updateOne({_id:req.params.id},{$set: {email: req.body.email});

But..

overtime this might be an exhaustive task if

  • You intend to use proposed method throughout all the APIs.
  • or if a model has number of field names and you're updating selectively.

I'd suggest to continue with your existing approach as long as

  • the req.body always has all the existing data on the document
  • Doesn't contain useful fields like createdAt or updatedAt otherwsie that may be updated..

To counter 2nd point, you could disallow unknown fields using Joi validation.

Source

about 4 years ago · Juan Pablo Isaza Denunciar

0

Please try this

  student = await Student.updateOne({_id:req.params.id},req.body);
about 4 years ago · Juan Pablo Isaza 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