无法调用未定义的方法推送(定义时)
我使用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
表示了阵列当它在模式中定义并且我正在回顾正确的用户(家伙)时?感谢您的帮助
看来,你的家伙对象实际上是一串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});
})
});
}
得到试图解析由蒙戈产生 '未定义的对象ID时的错误:1 {_id:5483d815ff8b74480f7dcf85, ^ 语法错误:意外的令牌_ 在Object.parse(天然) 在无极。
JSON是无效的,api给出的id不带引号,因为它是一个十六进制数字。 JSON解析看到它是一个没有引号的字符串,所以会引发错误。试着在_id之后加一个单引号,在第一个逗号之前加一个单引号,看看是否能解决问题。 – Simba 2014-12-07 04:35:55
对象'friendFound'是数据还是null? – 2014-12-07 04:27:09