2016-09-10 28 views
0

在nodecelar骨幹樣品的NodeJS,我有代碼:骨幹例如,Nodecelarr

exports.findById = function(req, res) { 
    var id = req.params.id; 
    console.log('Retrieving wine: ' + id); 
    db.collection('wines', function(err, collection) { 
    collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) { 
     res.send(item); 
    }); 
    }); 
    }; 

我有錯誤:

TypeError: Cannot read property 'findOne' of undefined.

你能不能幫我請。謝謝。

回答

0

無法讀取未定義的屬性'findOne'。

錯誤表示您正嘗試對未定義的變量調用findOne

db.collection('wines', function(err, collection) { 
    collection.findOne(...); 
}); 

您在collection上調用該函數,因此該位置的集合必須是未定義的。我的猜測是數據庫調用失敗,並且err不爲空。

解決方案

你應該讓快遞處理它,或者通過返回自己的錯誤消息處理錯誤。

// use the "next" callback 
exports.findById = function(req, res, next) { 
    var id = req.params.id; 
    console.log('Retrieving wine: ' + id); 
    db.collection('wines', function(err, collection) { 
     // let express handle the error for you 
     if (err) return next(err); 
     // or 
     if (err) res.send({ 'error': 'An error has occurred' }); 
     else { 
      collection.findOne({ '_id': new BSON.ObjectID(id) }, function(err, item) { 
       res.send(item); 
      }); 
     } 
    }); 
};