mongoose objectid to number mongoose objectid to number mongoose mongoose

mongoose objectid to number


This is untested, but I think you'd want to do something like this:

var idNum = parseInt(objectId.valueOf(), 16);

MongoDB ObjectIDs are essentially 12 byte hex strings. This makes them larger than the MAX_VALUE for a JavaScript Number (2^53), so you may run into errors with the conversion. But, it looks like Number.MAX_VALUE in my node.js environment (0.11.6) can handle that value. So you might be safe...

Why are you converting an Object ID to a Number though? You really shouldn't be performing arithmetic operations on an ObjectId...


I assume you want the unique id of the object as an integer/number (sometimes just a small easy to use integer for end-users). I had the same use case for ticket numbers. There are times when you want end-users to be able to refer directly to the record id but without those funky chars. So one could really want to convert it to a simple integer eg: 000001 instead of 5220bb43b754af4118000001.

Here I am mostly answering the question's title to help me and others, I hope it answers the question at large.

Actually for the above use case or most you don't need to convert the entire object id:

According to this https://devopslog.wordpress.com/2012/04/22/disassemblingreassembling-mongodb-objectids/

timestamp → Generation timestamp (4 bytes)machine → First 3 bytes of the MD5 hash of the machine host name, or of the mac/network address, or the virtual machine id.pid → First 2 bytes of the process (or thread) ID generating the ObjectId.inc → ever incrementing integer value.

In chars this translates to:

timestamp → 0-7machine → 8-13pid → 14-17inc → 18-23

Which means:

"5220bb43b754af4118000001"

is broken down to:

timestamp → 5220bb43machine → b754afpid → 4118inc → 000001

you may only need the inc part of the id or at least the timestamp and inc.

let objID = "5220bb43b754af4118000001";let id = objID.substr(18);console.log(id);// 000001// if parsed to int this becomes 1

Hope this helps someone.


try using the virtual id onstead of _id

option(data-id=val.id) #{val.name}

instead of

option(data-id=val._id) #{val.name}