NodeJS Mongoose - Cannot call method 'toString' of undefined
I am trying to print to console the name of a group in my database, here is the code:
var Team = require('../schemas/Team').Model;
app.get('/match', function(req, res) {
var key = 1359407087999; // Team Key
Team.findByKey(key, function(err, team) {
util.log(team);
if (err) {
util.log("Error occured");
}
if (!team) {
util.log("The team does not exist");
} else {
res.send("Found team: " + team.name);
}
});
});
The code receives the command successfully, where util.log(team)
. It prints this to the console:
{
__v: 0,
_id: 5106e7ef9afe3a430e000007,
name: 'Team Name',
key: 1359407087999
}
This also works when submitting it to a webpage.
But when I try to send the Team name to the webpage, I get the following output using the res.send
=> Found team: undefined
... method And when I try to output team.name
instead team
to the console, I get the errorCannot call method 'toString' of undefined
Here is my Mongoose schema of my command:
var Team = new Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'name' : { type : String,
validate : [validatePresenceOf, 'Team name is required'],
index : { unique : true }
}
});
Team.statics.findByKey = function(key, cb){
return this.find({'key' : key}, cb);
};
module.exports.Schema = Team;
module.exports.Model = mongoose.model('Team', Team);
show command
app.get('/show/team/:key', function(req, res){
util.log('Serving request for url[GET] ' + req.route.path);
Team.findByKey(req.params.key, function(err, teamData){
util.log(teamData[0]);
if (!err && teamData) {
teamData = teamData[0];
res.json({
'retStatus' : 'success',
'teamData' : teamData
});
} else {
util.log('Error in fetching Team by key : ' + req.params.key);
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Team by key ' + req.params.key
});
}
});
});
source to share