我正在尝试为餐厅预订mongoose架构,但我不希望人们能够预订,如果有人'所有收藏中的价值都超过50。
var reservationSchema = new mongoose.Schema ({
people: Number,
date: String,
name: String,
email: String
});
var Reservation = mongoose.model("Reservation", reservationSchema);
app.post('/reservation', (req, res) => {
var people = parseFloat(req.body.people);
var date = req.body.date;
var name = req.body.name;
var email = req.body.email;
var newReservation = {people: people, date: date, name: name, email: email};
Reservation.create(newReservation, (err, newlyCreated) => {
if(err) {
console.log(err);
}
else {
res.redirect('/');
}
})
});
如何过滤所有集合以查找从人们添加所有值时的数字是什么?
答案 0 :(得分:1)
您需要使用聚合管道来总计人数。如果计数小于50,请创建新预订,否则显示一些消息。
为此,您可以使用statics
方法。
var reservationSchema = new mongoose.Schema ({
people: Number,
date: String,
name: String,
email: String
});
reservationSchema.statics = {
createIfSpaceAvailable : function(newReservation, done){
var Reservation = this;
Reservation.aggregate([
{
$group:{
_id: null,
noOfPeople: { $sum: "$people"}
}
}],
function(err, result){
if(err){
return done(err);
}
else if(result[0].noOfPeople > 50){
// do something
}
else{
Reservation.create(newReservation, (err, newlyCreated) => {
if(err) {
return done(err);
}
else {
return done();
}
})
}
})
}
};
var Reservation = mongoose.model("Reservation", reservationSchema);
app.post('/reservation', (req, res) => {
var people = parseFloat(req.body.people);
var date = req.body.date;
var name = req.body.name;
var email = req.body.email;
var newReservation = {people: people, date: date, name: name, email: email};
Reservation.createIfSpaceAvailable(newReservation, (err, newlyCreated) => {
if(err) {
console.log(err);
}
else {
res.redirect('/');
}
})
});
答案 1 :(得分:0)
您可以使用聚合管道 - 请参阅:
,特别是$sum
运算符:
顺便说一句,因为Node v4.x而不是写:
var newReservation = {people: people, date: date, name: name, email: email};
您可以使用更短的语法:
var newReservation = {people, date, name, email};
请参阅: