ykn121 ykn121 - 11 months ago 233
Node.js Question

TypeError: Cannot read property 'findOne' of undefined

Here are the codes

var mongo = require('mongodb');

var databaseName = 'Starter',
collectionName = 'wines';

var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;

db = new Db(databaseName, server);

db.open(function(err, db) {
if(!err) {
console.log("Connected to 'winedb' database");
db.collection(collectionName, {strict:true}, function(err, collection) {
if (err) {
console.log("The 'wines' collection doesn't exist. Creating it with sample data...");

exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving wine: ' + id);

db.collection(collectionName, function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {


These codes are based on a sample of restful api for nodejs with mongoDB.
However, it seems that it cannot recognise the function
. Can someone point out the problem?

Error message:

TypeError: Cannot read property 'findOne' of undefined

Answer Source

findOne is deprecated in the latest version of mongodb@2.x


You can use this query instead

find(query).limit(1).next(function(err, doc){
   // handle data