2014-12-07 137 views
0

我使用Node.js和mongoose爲應用程序創建後端,用戶可以在其中互相通信。無法調用未定義的方法推送(定義時)

架構

var mongoose = require('mongoose'); 

    var Schema = mongoose.Schema; 

    var userSchema = mongoose.Schema({ 
    name : String, 
    nick: String, 
    reg_id: String, 
    friends: { 
     type: Array, 
     'default': [] 
    } 
    }); 
    mongoose.connect('mongodb://localhost:27017/DB'); 
    module.exports = mongoose.model('users', userSchema); 

請求

exports.addfriend = function(reg_id,friend,callback) { 

    user.find({reg_id:reg_id},function(err,guy){ 

    // found the user, now add his friend 
    user.find({name:friend}, function(err,friendFound){ 
     console.log("trying to add friend to:"+guy) 
     console.log("his current friends:"+guy.friends) 

     guy.friends.push(friendFound.reg_id) 
     callback({'response':guy.name+' is now friends with '+friendFound.name}); 
    }) 
    }); 
} 

控制檯爲什麼限定

trying to add friend to:{ _id: 5483d2c76dd64ee412bfe865, 
    name: 'Hello', 
    nick: 'hey', 
    reg_id: 'XXXXXXXXX', 
    __v: 0, 
    friends: [] } 
his current friends:undefined 

C:\..\config\requests.js:82 
     guy.friends.push(friendFound.reg_id) 
TypeError: Cannot call method 'push' of undefined 

表示了陣列當它在模式中定義並且我正在回顧正確的用戶(傢伙)時?感謝您的幫助

+0

對象'friendFound'是數據還是null? – 2014-12-07 04:27:09

回答

0

看來,你的傢伙對象實際上是一串JSON而不是JSON對象。嘗試在其上運行JSON解析

exports.addfriend = function(reg_id,friend,callback) { 

    user.find({reg_id:reg_id},function(err,guy){ 
    guy = JSON.parse(guy); //ADD THIS 
    // found the user, now add his friend 
    user.find({name:friend}, function(err,friendFound){ 
     console.log("trying to add friend to:"+guy) 
     console.log("his current friends:"+guy.friends) 

     guy.friends.push(friendFound.reg_id) 
     callback({'response':guy.name+' is now friends with '+friendFound.name}); 
    }) 
    }); 
} 
+0

得到試圖解析由蒙戈產生 '未定義的對象ID時的錯誤:1 {_id:5483d815ff8b74480f7dcf85, ^ 語法錯誤:意外的令牌_ 在Object.parse(天然) 在無極。 (C:\ Users \ Arin \ Documents \ reference \ node-chat \ node_mod ules \ config \ requests.js:76:16)' – Ray 2014-12-07 04:33:40

+0

JSON是無效的,api給出的id不帶引號,因爲它是一個十六進制數字。 JSON解析看到它是一個沒有引號的字符串,所以會引發錯誤。試着在_id之後加一個單引號,在第一個逗號之前加一個單引號,看看是否能解決問題。 – Simba 2014-12-07 04:35:55

相關問題