我正在学习Javascript,Node和Sails,并且有一个基本的newb(我认为)问题,我无法在其他地方找到答案。
在控制器中,我尝试访问特定的模型属性,然后创建一个包含每个单独条目的数组,以便在视图中使用。虽然我可以在菜单/索引视图中访问模型中的记录,但我似乎无法直接在模型中使用任何特定属性。
这里是有问题的控制器代码:
var MenuController = module.exports = {
manager: function(req, res) {
var userId = req.session.user.id;
sails.log("Searching for foods for user: "+ userId);
Menu.find({ where: { userId: { equals: userId }}}).exec(function(err, records) {
if(records && records.length == 0) {
sails.log("No foods found for user: " + userId);
sails.log(err);
return res.view("menu/index");
} else {
var foodCategories = records.food_category;
sails.log(foodCategories);
var array = foodCategories.split(',');
var foodCatArray = [];
for (i = 0; i < array.length; i++) {
foodCatArray.push(array[i].toUpperCase());
var uniqueCats = foodCatArray.filter(function (item, i, ar) {
return ar.indexOf(item) === i;
});
var sortedCats = uniqueCats.sort();
sails.log(sortedCats);
}
return res.view("menu/index", {foods: records, sortedCats: sortedCats});
}
});
},
以下是有问题的模型:
var Menu = module.exports = {
attributes: {
userId: {
required: true,
type: 'integer',
min: 1
},
food_category: {
type: "string",
required: false,
min: 1,
max: 200
},
food_name: {
type: "string",
required: true,
min: 1,
max: 200
},
food_cost: {
type: "string",
required: true,
min: 1,
max: 10
},
food_description: {
type: "string",
required: true
},
img_path: {
type: "string",
required: true
},
img_name: {
type: "string",
required: true
},
img_name_crypt: {
type: "string",
required: true
}
}
};
现在这一行:
var foodCategories = records.food_category;
当我加载菜单/索引视图时,在我的Sails日志中创建一个未定义的值。有人能指出我正确的方向吗?
答案 0 :(得分:1)
您的记录变量很可能是对象数组。
将代码移到for循环中并像
一样使用它records[i].food_category
你不需要var数组...... 在for循环中使用records.lenght而不是
答案 1 :(得分:1)
非常感谢Molda让我在正确的方向上轻轻推动!
这是最终为我工作的Sails控制器代码:
var MenuController = module.exports = {
manager: function(req, res) {
var userId = req.session.user.id;
sails.log("Searching for foods for user: "+ userId);
Menu.find({ where: { userId: { equals: userId }}}).exec(function(err, records) {
if(records && records.length == 0) {
sails.log("No foods found for user: " + userId);
sails.log(err);
return res.view("menu/index");
} else {
var foodCatArray = [];
for (i = 0; i < records.length; i++) {
var foodCategories = records[i].food_category;
foodCatArray.push(foodCategories);
}
var uniqueCats = foodCatArray.filter(function (item, i, ar) {
return ar.indexOf(item) === i;
});
uniqueCats.sort();
sails.log(uniqueCats);
sails.log("Returning " + records.length + " foods found for user: " + userId);
return res.view("menu/index",{ foods: records, foodCats:uniqueCats });
}
});
},
此代码循环遍历用户菜单条目中每个食物项目上的每个food_category字符串,将其添加到数组中,然后对数组进行排序,从而消除重复项并按字母顺序对数组进行排序。在我看来,我可以使用&#34; foodCats&#34;抓住这个数组,做任何我需要的东西。