2014-06-26 89 views
-2

我在我的appery.io應用程序中使用下面的JavaScript代碼。我不斷收到一個錯誤,指出以下內容:我的JavaScript代碼52行的錯誤,我不知道它

6/25/2014 9:37:35 PM: Script All_Users_Data: TypeError: Cannot read property '_id' of undefined (@ 52 : 33) -> if (all_photo[i].the_user._id == id) { 

請幫我指出錯誤。我試圖從3個集合中提取數據,通過_id從'用戶'集合同步它們,然後輸出用戶配置文件類型信息。

var all_users = eval(DatabaseUser.query('52895ecce4b056c5e94f34f9')); 
var all_profiles = eval(Collection.query('52895ecce4b056c5e94f34f9', 'profile')); 
var all_status = eval(Collection.query('52895ecce4b056c5e94f34f9', 'Status')); 
var all_photo = eval(Collection.query('52895ecce4b056c5e94f34f9', 'photo')); 

// loop on all users 
for (var i=0;i<all_users.length;i++) 
{ 
    // call function to search for user profile and then add first name to current user   item 
    getProfile(all_users[i]._id, all_users[i]); 
    // call function to search for user status and then add last status to current user item 
    getstatus(all_users[i]._id, all_users[i]); 
    getphoto(all_users[i]._id, all_users[i]); 
} 

// function get user item and user id and find user profile by its id and update it 
function getProfile(id,curUser) 
{ 
    var found = false; 
    for (var i = 0; i < all_profiles.length; i++) { 
     // if cur user id = profile id assign profile name to the user 
     if (all_profiles[i].the_user._id == id) 
     { 
      curUser.firstName = all_profiles[i].firstName; 
      curUser.university = all_profiles[i].university ; 

      found = true; 
     } 
    } 
    if (!found) 
    { 
     curUser.f_name = ""; 
    } 
} 

// function get user item and user id and find user status by its id and update it 
function getstatus(id, curUser) { 
    var found = false; 
    for (var i = 0; i < all_status.length; i++) { 
     if (all_status[i].the_user._id == id) { 
      curUser.status = all_status[i].status; 
      found = true; 
     } 
    } 
    if (!found) { 
     curUser.status = ""; 
    } 
} 
function getphoto(id, curUser) { 
    var found = false; 
    for (var i = 0; i < all_photo.length; i++) { 
     if (all_photo[i].the_user._id == id) { 
      curUser.photo = all_photo[i].photo; 
      found = true; 
     } 
    } 
    if (!found) { 
     curUser.photo = ""; 
    } 
} 

// return full user data updated wih status and first name 
response.success(JSON.stringify(all_users), "application/json"); 
+0

看起來像all_profiles中的the_user對象爲null。嘗試在控制檯中驗證結果,方法如下: console.log(all_profiles [i]); – Ash

+0

訪問對象的元素之前,應檢查它們是否已定義。 – Gabs00

+1

'eval()' - 等等,什麼?這很可能是此代碼中的前4個錯誤。 – Bergi

回答

1

這意味着,這是不確定的:

all_photo[i].the_user 

所以,因爲它是不確定的,它最肯定沒有財產_id,因爲不確定的對象有沒有屬性,因爲他們是不確定的。

這是否定義了問題的根源?

-

使用瀏覽器的控制檯 - 它可以幫助:

console.log(all_photo); 

然後你就可以檢查出什麼是與該對象和哪些屬性它確實有你eval之後發生的事情。

+0

非常感謝你的幫助,這有點幫助。我看到領主在哪裏關門票,但我仍然沒有清楚的理解爲什麼。不過,我想電源與他們:) – hero123

+0

問題修復!再次感謝提示! – hero123

+0

沒問題的人。 – dthree

相關問題