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.