I do not know if more than one field can be updated
Yes it is possible, in fact, it is a normal behavior.
If so, how would it be?
In mongoose there are two ways to update:
- Using the model
- Through an instance of the model
Update using the model
This form is what you are using. The update
Mongoose#Model
, receives the following two parameters as follows:
- Subject of conditions. These values are used to know which document will be updated.
- Object of new values. This object contains the new values to be saved.
It is advisable to use promises instead of callbacks with Mongoose
To update a document, simply:
Boleta.update(
{serie: serie},
{firma: parametros}
).then((rawResponse) => {
})
.catch((err) => {
// manejar error
});
The previous code updates the field firma
of the ballot with serie
"X". Keep in mind that parametros
must be exactly the same type of data that you have defined in the Boleta
model.
Note: The update
function does not return the updated document. Returns the flat response of MongoDB. This response contains data such as affected fields , etc.
Update by instance
This method is much simpler, as well as useful when you want to return the affected document. What you do here is find the document and add the new values with properties.
Boleta.findOne({
serie: req.params.id
})
.then((boleta) => {
boleta.firma = req.params.firma;
boleta
.save()
.then(() => {
res.jsonp({ boleta }); // enviamos la boleta de vuelta
});
});
I do not know if what I'm doing wrong or why it does not work for me
When an update does not occur in Mongoose it is mainly because a validation error has occurred . It usually occurs when we set invalid values for that property, for example, saving a text in a Number
field. When these cases occur, Mongoose launches a MongooseError
, which has all the error information that has happened. You can capture this error in a catch and manage it.
try {
// actualizar documento
} catch(e) {
let errors = e.errors;
res.jsonp({
errors,
success: false
});
}
Tip: Before proceeding to update, validate the incoming information, in such a way that you avoid possible runtime errors and so the user can know what errors in the validation have occurred.