Reputation: 41
When create a new ObjectId in my node.js script using:
mongojs.ObjectId()
I get an _id like
“f5818257dd0b55ce321f87b5”
When I use:
mongojs.ObjectId(“f5818257dd0b55ce321f87b5”).getTimestamp()
I get:
“Sun Jul 10 2016 19:12:21 GMT+0200 (CEST)"
But when I use ObjectId("f5818257dd0b55ce321f87b5").getTimestamp()
in the MongoDB Shell I get:
ISODate("2100-07-10T12:23:51Z")
When I want to sort my documents by _id
with:
db.stores.find().sort({_id: -1})
The documents are returned in the wrong order because the timestamp in the ObjectId
is wrong.
How do I get mongojs to produce ObjectIds
in the right format ?
I’m really confused, can anyone help me ?
Edit: When I insert a document with mongojs i get an ObjectId like:
“30a282576f9f2c4772e69cd9”
When I get the timestamp with:
ObjectId("30a282576f9f2c4772e69cd9").getTimestamp()
It returns:
ISODate("1995-11-09T22:36:07Z")
But when I insert a document using the MongoDB Shell i get an ObjectId like:
“5782a4809f3c4cbed9f2a8a1”
When I get the timestamp from this id using:
ObjectId("5782a4809f3c4cbed9f2a8a1").getTimestamp()
I get:
ISODate("2016-07-10T19:39:44Z")
These two documents are created like 5 min apart. Why is the date in the ObjectId inserted with mongojs wrong ?
Upvotes: 3
Views: 481
Reputation: 203574
This isn't really an answer, because I don't know who's at fault or how to properly fix it, but the cause is due to different byte orders.
Taking your 30a282576f9f2c4772e69cd9
example and switching endianness on it (see below) yields 5782a230472c9f6fd99ce672
, which is interpreted correctly in the MongoDB shell.
Here's the code:
let buf1 = Buffer.from('30a282576f9f2c4772e69cd9', 'hex');
let buf2 = Buffer.alloc(buf1.length);
[ 0, 4, 8 ].forEach(o => buf2.writeUInt32LE( buf1.readUInt32BE(o, 4), o ));
console.log(buf1.toString('hex'));
console.log(buf2.toString('hex'));
I don't think it has to do with mongojs, because that's just using the official MongoDB Node driver.
Upvotes: 4
Reputation: 41
Problem solved I was using version 2.2.0 of the MongoDB Node driver after updating to a newer version everything is working like expected.
Upvotes: 1