简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM