Javascript 无法调用未定义的方法push(在已定义时)
我正在使用Node.js和mongoose为一个应用程序创建一个后端,在这里用户可以彼此成为朋友 模式 请求 控制台Javascript 无法调用未定义的方法push(在已定义时),javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我正在使用Node.js和mongoose为一个应用程序创建一个后端,在这里用户可以彼此成为朋友 模式 请求 控制台 为什么数组在模式中定义时显示为已定义,而我正在检索正确的用户?感谢您的帮助看起来您的guy对象实际上是一个JSON字符串,而不是一个JSON对象。尝试对其运行JSON解析 exports.addfriend = function(reg_id,friend,callback) { user.find({reg_id:reg_id},function(err,guy){
为什么数组在模式中定义时显示为已定义,而我正在检索正确的用户?感谢您的帮助看起来您的guy对象实际上是一个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});
})
});
}
找到的对象是data还是null?尝试分析mongo未定义生成的对象ID时出错:1{u id:5483d815ff8b74480f7dcf85,^SyntaxError:Unexpected token{at Object.parse native at Promise.C:\Users\Arin\Documents\reference\node chat\node\node\modules\config\requests.js:76:16 JSON无效,api给出的id不带引号,因为它是一个十六进制数。JSON parse发现它是一个不带引号的字符串,所以将其删除引发错误。请尝试在_id:后加一个引号,在第一个逗号前加一个引号,看看这是否解决了问题。
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
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});
})
});
}