在Express中,我尝试扫描POST请求并创建数组openingTimes
。然后根据输入创建一个MongoDB文档。
以下代码段工作正常,但我如何制作循环而不是定义n天?
`module.exports.myController = function (request, response) {
MongoDBModel.create({
name: req.body.name,
//I want to make a loop in here, so I dont have to define each day separately
openingTimes: [{
days: req.body.days1
, opening: req.body.opening1
, closing: req.body.closing1
, closed: req.body.closed1
}, {
days: req.body.days2
, opening: req.body.opening2
, closing: req.body.closing2
, closed: req.body.closed2
}]
// catching errors
}, function (err, location) {
if (err) {
sendJsonResponse(res, 400, err);
console.log("error is " + err);
}
else {
sendJsonResponse(res, 201, location);
}
});
};`
答案 0 :(得分:1)
您可以预先创建数组(或使用返回数组的IIFE内联)。
<option><?php echo $row1['class']; ?></option>
或者使用ES6,您可以创造性地使用生成器功能制作IIFE。
var numDays = 7;
var openingTimes = [];
for (var i = 1; i <= numDays; i++) {
openingTimes.push({
days: reg.body['days' + i],
opening: req.body['opening' + i],
closing: req.body['closing' + i],
closed: req.body['closed' + i]
});
}
MongoDBModel.create({
name: req.body.name,
openingTimes: openingTimes
}, etc);