I have the following schematics:
const AutorSchema = new Schema({
nombre: {
type: String,
required: [true, "El nombre es requerido"]
},
apellido:{
type: String,
required: [true, "El apellido es requerido"]
}
})
const LibroSchema = new Schema({
titulo: {
type: String,
required: [true, "El titulo es requerido"]
},
editorial:{
type: String,
required: [true, "La editorial es requerida"]
},
autor:{
type: AutorSchema,
required: ["El autor es requerido"]
}
})
When I want to update the author information and I only want to modify one of the Author attributes, only the field I wanted to update is saved and the others disappear. For example:
const autor = {
data:{
apellido: "Perez"
}
}
Libro.findOneAndUpdate({_id: req.params.id}, autor);
/*
Devuelve =>
{
titulo: "Libro1",
editorial: "Editorial1",
autor:{
apellido: "Perez"
}
}
*/
As you can see the "name" attribute of the author disappears and only the new last name remains. How can I modify some of the attributes and keep the others?
As @JackNavaRow comments, you should use the operator
$set
to tell MongoDB that a field is being replaced and not the entire document.In addition, the field that you are going to update, since it is a field in an embedded document, you must indicate it using the dot notation.
For example:
I hope this helps you solve the problem.
EDITION
In your comment you ask a very interesting question.
If any of the
json
received fields isundefined
, then we should not do the update, since it sets the a fieldnull
in the document.The solution is to build the update object based on the information received.
For example:
Let's see an example of the above code working: