Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

278
Vistas
How do you update a referenced document in mongoose?

I'm creating a reservation system of sorts using mongoose and nodejs. There are a list of hotels which have number of available rooms as a field. While creating a new booking for a customer, I want to update the number of available rooms in the hotel by reducing it by 1, for example.

Here's my code:

Hotel Model File:

var hotel: new mongoose.Schema{
name: String, 
availableRooms: {type: Number, default: 1}}

Booking Model File:

var booking: new mongoose.Schema{
userName: String,
hotelId: {type: Schema.Types.ObjectId, ref: 'hotel'}
}

Here's the post operation that I'm having trouble with:

api.route('/booking').post(function(req,res){
hotel.findOneAndUpdate({id: req.body.hotelId, availableRooms: {$gt: 0}},
availableRooms: -1, function(err){
if (err) throw err})
booking.create(req.body, function(err, confirmedBooking){
if (err) throw err;
res.json(confirmedBooking)
});

Postman shows this error:

ReferenceError: hotel is not defined

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

There are multiple errors in your code:

  1. You might not have imported hotel schema in your node app(app.js/ server.js). The error from postman hotel is undefined is coming because of that.

If you have already imported, please check variable name, they are case sensitive, so check that too.

To import the hotel schema in your node app.:

var Hotel = require('path/to/hotel.js');
//OR
var Hotel = mongoose.model('Hotel');

Then try updating the document using Hotel, instead of hotel.

  1. you cant decrease the value of a field like that, you need to use $inc.

Try this:

var hotelId = mongoose.Schema.Types.ObjectId(req.body.hotelId);
// Dont forget to include mongoose in your app.js
Hotel.findOneAndUpdate({
    _id: hotelId, availableRooms: {$gt: 0}
},{
    $inc : { availableRooms : -1 }
}, function(err){
    if (err) throw err
    else
    {
        booking.create(req.body, function(err, confirmedBooking){
            if (err) throw err;
            res.json(confirmedBooking)
        });
    }
});

Update : I have moved the section to creat new booking inside the callback of update function, so that new booking gets created only when it is successfully updated. It's better to use this way

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda