Reputation: 61
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);
});
}
Upvotes: 1
Views: 1281
Reputation: 312129
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 ...);
}
Upvotes: 3