NodeJS + MongoDB: Getting data from collection with findOne ()

You need to construct the ObjectID and not pass it in as a string. Something like this should work:

var BSON = require('mongodb').BSONPure;
var obj_id = BSON.ObjectID.createFromHexString("4fcfd7f246e1464d05000001");

Then, try using that in your find/findOne.

Edit: As pointed out by Ohad in the comments (thanks Ohad!), you can also use:

new require('mongodb').ObjectID(req.params.id)

Instead of createFromHexString as outlined above.


You can use findById() which will take care of the id conversion for you.

company = Company.findById(req.params.id, function(err, company) {
    //////////
});

That's because _id field in mongo isn't of string type (as your req.params.id). As suggested in other answers, you should explicitly convert it.

Try mongoskin, you could use it like node-mongodb-native driver, but with some sugar. For example:

// connect easier
var db = require('mongoskin').mongo.db('localhost:27017/testdb?auto_reconnect');

// collections
var companies = db.collection('companies');

// create object IDs
var oid = db.companies.id(req.params.id);

// some nice functions…
companies.findById();

//… and bindings
db.bind('companies', {
  top10: function(callback) {
    this.find({}, {limit: 10, sort: [['rating', -1]]).toArray(callback);
  } 
});

db.companies.top10(printTop10);