问题描述
我正在使用猫鼬和nodejs创建各种各样的预订系统.有一些酒店,其中列出了可提供客房数量的字段.在为客户创建新的预订时,我要检查特定酒店中的可用客房数量是否大于0,如果是,请通过将其减少1来更新酒店中的可用客房数量.
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 check if the number of available rooms in the particular hotel greater than 0 and if it is, update the number of available rooms in the hotel by reducing it by 1.
这是我的代码
-酒店模型文件
var hotel: new mongoose.Schema{
name: String,
availableRooms: {type: Number, default: 1}}
-预订模型文件
var booking: new mongoose.Schema{
userName: String,
hotelId: {type: Schema.Types.ObjectId, ref: 'hotel'}
}
这是我遇到麻烦的代码.
Here's the code I'm having trouble with.
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)
});
}
});
当我尝试使用邮递员创建新预订时,它会创建新预订,但不会检查可用客房选项.如果酒店的可用房间为零,它仍会继续创建预订.另外,可用房间的数量根本不会低于0.
When I try to create a new booking using postman, it creates the new booking but it doesn't check the available rooms option. If a hotel has zero available rooms, it still goes on to create the booking. Also, the number of available rooms doesn't go below 0 at all.
推荐答案
遍历代码,在 findOneAndUpdate()
回调,因为您的代码不会产生任何错误,它只是不检查是否有来自的匹配文档更新查询.
Going through your code, the else
clause in the findOneAndUpdate()
callback is always executed because your code doesn't produce any error, it just isn't checking if there is a matching document from the update query.
您需要检查是否有匹配的文件,以及原始文件是否有可用于您创建新预订的房间.
You need to check is there is a matching document as well as if the original document has available rooms for you to create the new booking.
以下代码实现了规范:
{ '_id': hotelId, 'availableRooms': { '$gt': 0 } },
,如果是,则
{ '$inc': { 'availableRooms': -1 } },
if (hotel && hotel.availableRooms > 0) { /* create booking */ }
正确的更新
Hotel.findOneAndUpdate(
{ '_id': hotelId, 'availableRooms': { '$gt': 0 } },
{ '$inc': { 'availableRooms': -1 } },
function (err, hotel) {
if (err) throw err;
else if (hotel && hotel.availableRooms > 0) {
booking.create(req.body, function(err, confirmedBooking){
if (err) throw err;
res.json(confirmedBooking);
});
}
}
);
这篇关于猫鼬的findOneAndUpdate函数似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!