3

データベース内のチームの名前をコンソールに出力しようとしています。コードは次のとおりです。

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);
        }
    });
});

コードはチームを正常に取得しutil.log(team)ます。これをコンソールに出力します。

{
    __v: 0,
    _id: 5106e7ef9afe3a430e000007,
    name: 'Team Name',
    key: 1359407087999 
}

これは、Web ページに送信する場合にも機能します。

しかし、チームの名前をWebページに送信しようとすると、res.sendメソッド=>で次の出力が得られFound team: undefinedます...コンソールのteam.name代わりに出力しようとすると、エラーが発生しますteamCannot call method 'toString' of undefined

これも私のチームマングーススキーマです:

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);

ショーチーム

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
            });
        }
    });
});
4

1 に答える 1

2

名前は一意であるため、findOneの代わりに使用する必要がありfindます。

Team.statics.findByKey = function(key, cb){
  return this.findOne({'key' : key}, cb);
};
于 2013-02-07T13:42:39.353 に答える