First, make sure you add all the necessary modules to your MongoDB configuration:
var mongo = require('mongodb'), Server = mongo.Server, Db = mongo.Db, ObjectID = require('mongodb').ObjectID; var BSON = require('mongodb').BSONPure; var server = new Server('localhost', 27017, { auto_reconnect: true }); var db = new Db('YOUR_DB_NAME', server);
Then, when you try to find an object in the collection using _id, use:
//let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'... var obj_id = BSON.ObjectID.createFromHexString(id); db.collection("NAME_OF_COLLECTION_WHERE_IS_YOUR_OBJECT", function(error, collection) { collection.findOne( {_id:obj_id} , function(err, item) { // console.log ( item.username ); }); });
Hope this works.
f1nn
source share