我有一个空数据库并且我得到 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);
});
}