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

114
Vistas
findOneAndUpdate - How do I just update one field without altering the rest?

I am trying to create a CRUD app with React. I want a logged in user to be able to update details of their dog, however when I use the findOneAndUpdate function if I update a certain field it will remove the rest unless they are also specified.

My data is stored as such in a Schema:

const DogSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
  },
  dogsName: {
    type: String,
    required: true,
  },
  // Dogs details
  dogsDetails: {
    dogsBreed: {
      type: String,
    },
    microchip: {
      hasChip: {
        type: Boolean,
      },
      microchipNumber: {
        type: String,
      },
    },

This data is then destructerd in my routing file and built into an object called "dogFields" and when I use the following code to update it simply removes all fields unless I have specifically updated them (apart from dogsName which seems to stick)

try {
      let dog = await Dog.findOneAndUpdate(
        { user: req.user.id },
        { $set: dogFields },
        { new: true }
      );

Lets assume that my user has a dog set up with the "dogsName" of "Archer", and I go to update with "dogsBreed. This will update the "dogsBreed" field and keep the "dogsName". However if I then go to update the "hasChip", it will remove "dogsBreed".

I hope this makes sense, and that I have provided enough of my code as an example. Any help is appreciated. TIA.

about 4 years ago · Juan Pablo Isaza
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