Javascript - Node.js - Express - MongoDB - mongoose
I have a forEach() method that runs a for loop on each user adding/removing items in an array. It successfully adds the appropriate amount of items for one user, but fails to add the rest of the items. How is taskList.title 'undefined' with items remaining inside the Array?
User.find({}, function(err, allUsers){
if(err){
console.log(err);
} else {
console.log("Total Users: ", Number(allUsers.length));
console.log("Users are: ", allUsers);
Task.find({}, function(err, taskList){
if(err){
console.log(err);
} else {
console.log("Your task list: " , taskList);
console.log("First item: " , taskList[0].title);
let n = (Math.floor(Number(taskList.length) / Number(allUsers.length)));
console.log("Users have", n , "items.");
console.log("===============================");
//assign n items to each user
//line 151
allUsers.forEach(function addItem(user){
for(var i = 0; i < n; i++){
user.items.push(taskList[i].title);
taskList.splice(i,1);
console.log('item added!');
console.log(user.name+":", user.items);
console.log(taskList.length , "items remain.";
}
});
}
});
}
});
events.js:160
throw er; // Unhandled 'error' event
^
TypeError: Cannot read property 'title' of undefined
at addItem (/home/ubuntu/workspace/v1.4/app.js:151:56)
at Array.forEach (native)
at /home/ubuntu/workspace/v1.4/app.js:149:30
at /home/ubuntu/workspace/v1.4/node_modules/mongoose/lib/model.js:4485:16
at process.nextTick (/home/ubuntu/workspace/v1.4/node_modules/mongoose/lib/helpers/query/completeMany.js:35:39)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)