TypeError:无法读取未定义的属性“ title”

时间:2018-08-28 20:27:27

标签: javascript node.js mongodb express mongoose

Javascript-Node.js-Express-MongoDB-mongoose

我有一个forEach()方法,该方法在每个用户添加/删除数组中的项目时运行for循环。它成功为一个用户添加了适当数量的项目,但没有添加其余项目。如何将taskList.title'undefined'保留在数组中的项目?

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)

1 个答案:

答案 0 :(得分:1)

当使用TaskList.splice(i,1)时,您正在更新TaskList数组的长度,但是 for 循环未引用TaskList.length。您正在使用 n 中的缓存值,该值是原始TaskList.length值。

您将不需要使用 splice (剪接)或使用其他循环方法。也许有些使用Array.prototype.shift

var task;
while(task = TaskList.shift()) {
   ...
}