如何在继续发布路线之前检查是否存在mongo / mongoose值?
我的(部分)Mongoose模型如下所示:
reserved: {type: Boolean, default: false}
module.exports = mongoose.model("Rentals", rentalsSchema);
我一直试图以这种方式检查保留是否属实,没有任何运气
注意:正如您在下面看到的那样,这需要适用于每个租赁ID,因此需要以某种方式查找BYId。
router.put("/:id/reserve", middleware.checkRentalsStatus, function(req, res){
//checking here for existing value
//checking here for existing value
if(Rentals.reserved == true){
res.redirect("back");
console.log('TAKEN!')
} else {
// Token is created using Stripe.js or Checkout!
// Get the payment token submitted by the form:
var token = req.body.stripeToken; // Using Express
// Charge the user's card:
var charge = stripe.charges.create({
amount: 19500,
currency: "usd",
description: "",
source: token,
}, function(err, charge) {
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
var reservedby = req.body.reservedby;
var reserved = true;
var reservedemail = req.body.reservedemail;
var newReservation = {reserved: reserved, reservedby: reservedby, reservedemail: reservedemail }
Rentals.findByIdAndUpdate(req.params.id, {$set: newReservation}, function(err, rentals){
if(err){
req.flash("error", err.message);
res.redirect("back");
} else {
req.flash("success","It's reserved for you. Thank you!");
res.redirect("/rentals/" + rentals._id);
}
});
}
});
console.log('charged')
});
如何在完成邮政路线之前更改我的代码以检查保留是否为真? (我试图检查后端的预留路线是否有租金。)
答案 0 :(得分:-1)
你可以直接检查if / else是否像这样
if(Rentals.reserved )
{ res.redirect("back"); console.log('TAKEN!') }
else { // continue with post route
}
答案 1 :(得分:-1)
这就是答案。最好的方法是创建一个中间件来检查。其他答案的问题是他们没有找到肾脏的ID。 Rentals.findByID是实现这项工作的关键。 :)
//CHECK Rentals HAS NOT BEEN RENTED
middlewareObj.checkRentalsStatus = function(req, res, next){
Rentals.findById(req.params.id, function(err, foundRentals){
if (err){
res.redirect("back");
}
if (foundRentals.reserved){
req.flash("error", 'Oh no! It looks like someone else JUST rented this location. Your credit card was not charged.');
res.redirect("back");
} else {
next();
}
});
}