我使用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 :(得分:0)
看来你的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});
})
});
}