【发布时间】:2014-12-16 15:14:20
【问题描述】:
我正在编写一个快速应用程序,它允许某人创建一个食谱(烹饪食谱),然后将其保存到 mongodb。当他们打开应用程序时,他们可以看到食谱列表、编辑它们、删除它们等等。
菜谱像这样存储在 mongo 中
> db.recipes.find()
{ "_id" : ObjectId("542fc7d635ebd51b8afd507b"), "name" : "chili",
"ingredients" : [
{ "ingredient" : "mince", "quantity" : "500", "unit" : "g" },
{ "ingredient" : "cumin", "quantity" : "1", "unit" : "tsp" },
{ "ingredient" : "paprika", "quantity" : "2", "unit" : "tsp" } ]
}
{ "_id" : ObjectId("542fccbb6de6181f8da58346"), "name" : "test",
"ingredients" : [
{ "ingredient" : "stuff", "quantity" : "10", "unit" : "g" },
{ "ingredient" : "stuff", "quantity" : "10", "unit" : "g" } ]
}
每当查看“食谱”页面时都会读取数据库
router.get('/recipes', function(req, res) {
db.collection('recipes').find().toArray(function(err, results) {
if(results.length > 0) {
recipes = results;
for(var i = 0; i < results.length; i++) {
recipeList[i] = results[i].name;
}
res.render('recipes', {recipes: recipes, recipeList: recipeList});
} else {
recipes = [];
res.render('recipes', {recipes: recipes, recipeList: recipeList});
}
});
});
然后在recipes.jade 中列出的食谱如下
table.table
thead
tr
th Name
tbody
- for(var i = 0; i < recipes.length; i++)
tr
td= recipes[i].name
当点击这些配方之一时,一个模态将按如下方式启动
script("type=text/javascript").
$('td').on('click', function() {
var recipe = $(this).clone().children().remove().end().text();
$('#myModalLabel.modal-title').html(recipe);
$('#myModal').modal();
});
应该列出成分
当我点击食谱时,我很难弄清楚如何显示食谱的成分。我试图通过在模态中添加此代码来解决这个问题,我知道这是错误的,但我不知道要更改什么。
p ingredients
- for(var j = 0; j < recipes.length; j++)
ul
li= recipes[j].ingredients[0].ingredient
按照纳安的回答,稍作修改,我现在有一个单独的模板文件singleRecipe.jade
- var theIngredients = recipes[recipeIndex].ingredients;
p ingredients
ul
- for(var j = 0; j < theIngredients.length; j++)
li= theIngredients[j].quantity + theIngredients[j].unit + ' ' + theIngredients[j].ingredient
所以当一个配方被点击时,这个处理程序会获取名称和索引
$('td').on('click', function() {
var recipeIndex = $(this).parent().index();
var recipeName = $(this).text();
$('#myModal .modal-body').load('/singleRecipe/' + recipeIndex, function() {
$('#myModal').modal();
});
});
app.js 中的路由处理程序现在是
router.get('/singleRecipe/:d', function(req, res) {
db.collection('recipes').find().toArray(function(err, results) {
if(results.length > 0) {
recipes = results;
for(var i = 0; i < results.length; i++) {
recipeList[i] = results[i].name;
}
res.render('singleRecipe', {recipes: recipes, recipeIndex: req.params.d});
} else {
recipes = [];
res.render('recipes', {recipes: recipes, recipeList: recipeList});
}
});
});
我知道这仍然很混乱,但它的工作方式如下所示,所以现在我可以开始重构了。
【问题讨论】:
标签: javascript html mongodb express pug