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 
}

这也适用于将其发送到网页时。

但是当我尝试将团队的名称发送到网页时,我使用res.send方法 =>得到以下输出Found team: undefined...当我尝试输出team.name而不是team控制台时,我得到了错误Cannot 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 回答