Update a document with mongoose

0

Greetings community.! I'm making a small application using node and mongoose and I want to update a specific field of a document ie:

I have a document called Libro with a property ejemplares_disponibles of type number , what I want to do is update that property every time a user loaned a book, something like: ejemplares_disponibles -= 1 . I tried the Libro.findByIdAndUpdate(id, {}); method but I do not know how to subtract -1 from that property.

    
asked by Darwin Quiroz 21.08.2017 в 18:28
source

1 answer

0

Assuming you have the model of your Book (s) collection defined, one way is to do it like this:

    let libroId = req.params.libroId // el endpoint de tu API es del tipo /libros/:libroId, o sea que recibe por URL el ID del documento a actualizar

   // Primero lo buscas por su ID
   Product.findById(libroId , (err, libro) => {
     if (err) return res.status(500).send({message: 'Error al realizar la petición: ${err}'})

     // Aquí le restas menos uno lo que tenga ejemplares_disponibles
     libro.ejemplares_disponibles -= 1

     // Save te actualiza el documento si existe, sino, lo inserta. Pero en este caso lo actualiza porque primero lo busca
     libro.save((err, updatedLibro) => {
       if (err) res.status(500).send({message: 'Error al actualizar ${err}'})
       res.status(200).send( { updatedLibro} )
     })

   })

Basically, you first look for it by its ID, then modify the desired attribute and finally update it.

    
answered by 21.08.2017 / 19:00
source