NodeJS Mongoose - 无法调用未定义的方法'toString'

时间:2013-02-07 13:33:44

标签: javascript mongodb mongoose

我正在尝试在控制台中打印出我的数据库中Team的名称,这里是代码:

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 method =>获得以下输出: Found team: undefined ...当我尝试将team.name而不是team输出到控制台时,我收到错误Cannot call method 'toString' of undefined

这也是我的团队mongoose架构:

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

1 个答案:

答案 0 :(得分:2)

名称是唯一的,因此您应使用findOne代替find

Team.statics.findByKey = function(key, cb){
  return this.findOne({'key' : key}, cb);
};