1

我有一个空数据库并且我得到 TypeError: Cannot read property 'id' of undefined

我不确定如何检查未定义的变量,或者即使此检查应该在 db 模型中

特快路线

    app.all("/", function(req, res){  
      if(!req.isAuthenticated()) req.user = null;    
      Bid.findHighestBids(function(err, bids){
        if(err) throw err;
        User.findHighestBidder(bids[0].id, bids[0].amount, function(err, highest){
          if(err) throw err;
          highest.amount = bids[0].amount;  
          res.render("home", {user: req.user, bids: req.bids, highest: highest}); 
        });      
      });
    });

来自模型的片段,(没有数据,所以它没有返回任何东西,这就是问题所在)

    BidSchema.statics.findHighestBids = function(done){
      var Bids = this; 
      var num = 5;  
      this.find()
      .sort('-amount')
      .limit(num)
      .exec(function(err,bids){
        if(err) throw err;
        done(null, bids);
      });   
    }

    UserSchema.statics.findHighestBidder = function(id, amount, done){
      var User = this; 
      this.findOne({ 'facebook.id' : id }, function(err, highest){
        if(err) throw err;
        if(!id) return done(null, highest);
        done(null, highest);
      });  
    }
4

1 回答 1

3

bids在访问第一个元素之前,您没有检查包含任何元素。既然你说你没有数据,那很可能是你的问题:

Bid.findHighestBids(function(err, bids){
  if(err) throw err;
  User.findHighestBidder(bids[0].id, bids[0].amount, function(err, highest){
  ...

bids[0]return undefined,它没有id属性,因此错误。

所以改为这样做:

Bid.findHighestBids(function(err, bids){
  if (err) throw err;
  if (bids.length) {
    User.findHighestBidder(bids[0].id, bids[0].amount, function(err, highest){
      if(err) throw err;
      highest.amount = bids[0].amount;  
      res.render("home", {user: req.user, bids: req.bids, highest: highest}); 
    });      
  } else {
    res.render(... whatever you need for the no bids case ...);
  }
于 2013-09-03T01:20:20.040 回答