3

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 ?

  • 1
    What version of the MongoDB Node.js driver are you using? I can reproduce this incorrect behaviour with the 2.2.0 Node driver (and raised https://jira.mongodb.org/browse/NODE-749), but 2.1.21 and older versions seem fine. – Stennie Jul 11 '16 at 04:53
  • 1
    Thanks i was indeed using mongodb 2.2.0 i updated to 2.2.1 and now it's working like expected. – Patrick Keller Jul 11 '16 at 11:32

2 Answers2

4

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.

robertklep
  • 198,204
  • 35
  • 394
  • 381
1

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.