1

I have an empty database and im getting TypeError: Cannot read property 'id' of undefined

Im not sure how to check for a undefined variable, or even if this check should be in the db model

Express route

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

Snippet from the models, (there is no data so its not returning anything, which is the problem)

    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);
      });  
    }
1
  • 2
    reduce your code to a minimal bit of code that still exhibits the problem (serious. Do this. Don't just look at it and assume you know how it'll behave in reduced form). In the process of doing so, you're almost guaranteed to discover what went wrong yourself. Commented Sep 3, 2013 at 1:13

1 Answer 1

3

You're not checking that bids contains any elements before accessing the first one. Since you say you have no data, that's likely your problem:

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

bids[0] returns undefined, which has no id property, and thus the error.

So do something like this instead:

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 ...);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

It would be more helpful if you were to provide the if(bids).. solution/hint as well.
@slebetman True enough...I added an example of the sort of thing to do to fix it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.