I'm learning Javascript, Node and Sails, and have a basic newb (I think) question that I couldn't find an answer to elsewhere.
In a controller, I'm trying to access a specific model attribute and then create an array that includes each separate entry for use in a view. While I can access the records in my model in my menu/index view, I can't seem to work with any specific attribute directly in the model.
Here's the controller code in question:
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});
}
});
},
And here's the model in question:
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
}
}
};
Right now this line:
var foodCategories = records.food_category;
creates an undefined value in my Sails log when I load the menu/index view. Can someone point me in the right direction?
Your records variable is most probably array of objects.
Move the code inside the for loop and use it like
you don't need the var array ... In for loop use records.lenght instead