【发布时间】:2018-04-07 23:34:33
【问题描述】:
所以这就是问题所在。我有一个处理预订创建的 REST API,但是,在将预订保存到 mongo 之前,它会验证是否与另一个预订发生冲突。
exports.create = function(req, res) {
var new_type = new Model(req.body);
var newBooking = new_type._doc;
//check if the new booking clashes with existing bookings
validateBooking.bookingClash(newBooking, function(clash){
if(clash == null) // no clashes, therefore save new booking
{
new_type.save(function(err, type) {
if (err)
{
res.send(err); //error saving
}
else{
res.json(type); //return saved new booking
}
});
}
else //clash with booking
{
//respond with "clashDate"
}
});
};
这里有验证功能,可以检查当天是否与预订发生冲突:
exports.bookingClash = function (booking, clash) {
//find the bookings for the same court on the same day
var courtId = (booking.courtId).toString();
Model.find({courtId: courtId, date: booking.date}, function(err, bookings) {
if(err == null && bookings == null)
{
//no bookings found so no clashes
clash(null);
}
else //bookings found
{
//for each booking found, check if the booking start hour falls between other booking hours
for(var i = 0; i<bookings.length ; i++)
{
//here is where I check if the new booking clashes with bookings that are already in the DB
{
//the new booking clashes
//return booking date of the clash
clash(clashDate); //return the clashDate in order to tell the front-end
return;
}
}
//if no clashes with bookings, return null
clash(null);
}
});
};
因此,所有这些都适用于一个新的预订。但是,现在我希望能够处理递归预订(每周进行的预订)。我重新创建了“create”函数并在for loop 中调用了validateBooking.bookingClash 函数。
不幸的是,当我运行它时,它完美地调用了 bookingClash 函数,但是当它到达在数据库中进行搜索的行时:
Model.find({courtId: courtId, date: booking.date}, function(err, bookings)
它不等待回调并且在处理响应“冲突”之前,使 i++ 并继续。
如何让它工作并等待回调?
var array = req.body;
var clashes = [];
for(var i = 0; i<array.length;i++)
{
validateBooking.bookingClash(array[i], function(clash)
{
if(clash)
{
clashes.push(clash);
}
else{
console.log("no clash");
}
}
}
【问题讨论】:
标签: javascript node.js mongodb mongoose callback