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

112
Views
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
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!