Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9245935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T09:22:35+00:00 2026-06-18T09:22:35+00:00

I have this mongo-db.js file: var MongoClient = require(‘mongodb’).MongoClient, ObjectID = require(‘mongodb’).ObjectID; exports.MongoDB =

  • 0

I have this mongo-db.js file:

var MongoClient = require('mongodb').MongoClient,
    ObjectID = require('mongodb').ObjectID;

exports.MongoDB = function() {
    this.DB_NAME = "myDBNAME";
    this.MongoClient = MongoClient;

    return this;
};

exports.MongoDB.prototype.openDB = function(action) {
    console.log("Open DB");
    var scope = this;
    this.MongoClient.connect(this.generateMongoUrl(), function(err, db) {
        if (!err) {
            console.log("Open DB Success");
            if (action && typeof action === "function") {
                action(db, scope);
            }
        } else {
            console.log("DB Connect Error: " + err);
        }
    });
};

exports.MongoDB.prototype.closeDB = function(db, action) {
    var scope = this;
    return function() {
        console.log("Close DB and apply action with arguments");
        db.close();
        action.apply(this, arguments);
    };
};

exports.MongoDB.prototype.getItemById = function(id, callback) {
    this.openDB(function(db, scope) {
        console.log("Retrieving item: " + id);
        db.collection("items", function(err, collection) {
            if (err) { callback(err); }
            else {
                collection.findOne({ _id: ObjectID.createFromHexString(id) }, scope.closeDB(db, callback));
            }
        });
    });
};

exports.MongoDB.prototype.getAllItems = function(callback) {
    this.openDB(function(db, scope) {
        console.log("Retrieving all items");
        db.collection("items", function(err, collection) {
            if (err) { callback(err); }
            else {
                collection.find({ }).toArray(scope.closeDB(db, callback));
            }
        });
    });
};

And I run the following:

var scope = this;
var _items = [];
var counter = 0;

var done = function() {
    console.log("done!");
};

var getItem = function(error, item) {
    if (error) { }
    else {
        console.log("done loading item " + item._id);
        _items.push(item);
        if (_items.length === counter) {
            done();
        }
    }
};

this.db.getAllItems(function(error, items) {
    if (error) { }
    else {
        for (var i = 0; i < items.length; i++) {
            var id = items[i]._id;
            if (id) {
                counter++;
                console.log("load item " + id);
                scope.db.getItemById(id, getItem);
            }
        }
    }
});

When running this code I get:

Open DB
Open DB Success
Retrieving all items
Close DB and apply action with arguments
load item 50fb26263d47b70000000001
Open DB
load item 50fb277f172a5d0000000001
Open DB
load item 50fb2aa7865d870000000001
Open DB
load item 5102b7ddfe581ce5c7000001
Open DB
load item 5109678839aefde9fe000001
Open DB
load item 51096a91d0b50572ff000001
Open DB
load item 51096b06405d398bff000001
Open DB
load item null
Open DB
load item 51098b6b58bc1d0000000001
Open DB
load item 51098e16fb0e710000000001
Open DB
load item 51098e31a725100000000001
Open DB
load item 510991f20bc7690000000001
Open DB
load item 51099261258c710000000001
Open DB
load item 5109928b7edf7a0000000001
Open DB
load item 510992f0c73ccc0000000001
Open DB
load item 51099336e8a0090000000001
Open DB
load item 5109938d5fc9ce0000000001
Open DB
load item 510993cc8159610000000001
Open DB
load item 51099530ab74fb0000000001
Open DB
load item 5109956e8b059e0000000001
Open DB
load item 510995965f38da0000000001
Open DB
load item 510995ca14c0610000000001
Open DB
load item 5109963f2acd750000000001
Open DB
load item 5109966fc7001b0000000001
Open DB
Open DB Success
Retrieving item: 5109928b7edf7a0000000001

/myproj/node_modules/mongodb/lib/mongodb/connection/server.js:481
        throw err;
              ^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
    at Function.createFromHexString (/myproj/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:212:11)
    at exports.MongoDB.getItemById (/myproj/js/mongo-db.js:95:52)
    at Db.collection (/myproj/node_modules/mongodb/lib/mongodb/db.js:496:44)
    at exports.MongoDB.getItemById (/myproj/js/mongo-db.js:92:12)
    at exports.MongoDB.openDB (/myproj/js/mongo-db.js:72:17)
    at MongoClient.connect (/myproj/node_modules/mongodb/lib/mongodb/mongo_client.js:112:5)
    at _finishConnecting (/myproj/node_modules/mongodb/lib/mongodb/db.js:2126:7)
    at Db.open (/myproj/node_modules/mongodb/lib/mongodb/db.js:249:14)
    at Server.connect.connectCallback (/myproj/node_modules/mongodb/lib/mongodb/connection/server.js:277:7)
    at g (events.js:192:14)

When I put console.log(typeof id); before Object.createFromHexString(...), I get Object.
Trying to change the id by doing id=id+""; made the same error.

Why do I get this error?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T09:22:36+00:00Added an answer on June 18, 2026 at 9:22 am

    When using the MongoClient, the documents returned contain BSON ObjectID values and not strings. A BSON ObjectId using the native MongoClient has a structure like:

    _id = {
        id : "{12 bytes of binary data}",
        _bsontype : "ObjectID"
    }
    

    So, if you try to run it on the createFromHexString method, it will crash, as it’s already a BSON ObjectID.

    Here’s a simple example showing how no conversion is necessary from the Id that was returned originally.

    var
        mongodb = require('mongodb'),
        MongoClient = mongodb.MongoClient;
    
    MongoClient.connect("mongodb://localhost:27017/default?w=1", function (err, db) {
        db.collection("research").find({}, {'_id' : 1}).toArray(function(err, results) {
            results.forEach(function(doc) {
                console.log(doc._id + " type " + typeof doc._id);
                // now async get all docs            
                db.collection("research").findOne({'_id': doc._id}, function(err, doc) {
                    console.log("# " + doc._id);
                    console.log(doc);
                });
            });
    
        });
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Running this command in the mongodb installation file from mongodb.org ./mongo ds045907.mongolab.com:45907/database -u user
I have this line: @users = database['users'].find(:all).limit(10) it returns this object: <Mongo::Cursor:0x8759a858 namespace='app-development.users' @selector=:all
I am using the Mongo Ruby driver and have this block of Ruby code
I have a database connection that I got like this: db = Mongo::Connection.new.db(app-development) but
I have mongo documents in this format. {_id : 1,Summary : {...},Examples : [{_id
I have many collections of documents in a mongo database that look like this:
I am trying to use Properties file to parameterize connection to Mongodb. I have
I have a Rails app that saves files in mongo. This works great and
I have a function defined called func1 in file file_a.js I have another file
I have solr with sunspot_mongo gem. When I try run sunspot:mongo:reindex I get this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.