I am having an issue with displaying the name of a Team from my database on the web page. Here is the code snippet I am using:
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("An error occurred");
}
if (!team) {
util.log("The team does not exist");
} else {
res.send("Found team: " + team.name);
}
});
});
When I log the retrieved Team object using util.log(team)
, it shows the following information in the console:
{
__v: 0,
_id: 5106e7ef9afe3a430e000007,
name: 'Team Name',
key: 1359407087999
}
The code works well when displaying the data on the console and on the web page too.
However, I encounter a problem when trying to show the Team's name on the web page. The output I get is Found team: undefined
when using the res.send
method. Also, when replacing team
with team.name
in the console log, I receive an error saying
Cannot call method 'toString' of undefined
Here is the mongoose schema for my Team:
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 team
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
});
}
});
});