MongoDB NodeJS Driver? ObjectId().toString acts as ObjectId().valueOf() and vice-versa

I’m using the “mongodb” package from NPM version ^4.1.3.

I seem to have an issue where I get a document from the database and calling console.log(document._id.toString()) on it logs an ID like “abcdefg12345”. Calling console.log(document._id.valueOf()) logs "new ObjectId(“abcdefg12345”).

I believe the intended behaviour is the reverse, according to the docs at https://docs.mongodb.com/manual/reference/method/ObjectId/. valueOf should return a plain ID and toString should return the new ObjectId('id') thing.

Some further information:

  • I’m using the official docker image of mongodb
  • when I save a document, I’m letting MongoDB generate its default _id. I haven’t touched that property.
  • I get the document from the database using const document = await db.collection('collectionName').findOne({_id: ObjectId(plainIdOfDocument)}). Then I call document._id.toString() or document._id.valueOf() and I get the behaviour described above.

Am I doing something wrong, or am I missing something?

Please help, thank you :slight_smile:

I think you’re right.
It seems like it’s a mistake in the documentation.

Thanks,
Rafael,

1 Like