ykn121 ykn121 - 2 months ago 24
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...");
populateDB();
}
});
}
});

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) {
res.send(item);
});
});

};


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

Error message:

TypeError: Cannot read property 'findOne' of undefined

Answer

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

https://github.com/mongodb/node-mongodb-native/blob/2.0/lib/collection.js

You can use this query instead

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