Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda