vanDeurs
vanDeurs

Reputation: 55

Why does mongoose return object IDs' in the form of an object with an ID as a Buffer instead of string?

I have a static method in my UnitSchema that finds a unit by a token. It gets passed a token as a parameter and tries to find the unit with a normal findOne method on the Unit model:

UnitSchema.statics.findByToken = async function (token) {
  const Unit = this
  let unit = await Unit.findOne({ 'Tokens.token': token }).populate('Organisation')
  return unit
}

I have had this method for a long time and it has always returned the correct object. Now, which seems like all of a sudden for no reason, it returns a "complete" mongoose object with all of the extra information and functions, and all the object ID's are now in an object format instead of a string format, such as:

ObjectID {
  _bsontype: 'ObjectID',
  id: <Buffer 5c 85 43 16 f1 ad 70 d8 f8 97 48 78> 
}

instead of:

_id: '5d49595246853f14fc5168e9'

Because of this I can no longer populate fields with the normal: .populate('field') and this breaks my code.

I have searched around like crazy but can not find an explanation for this, and therefore I do not know how to fix it. Help is kindly appreciated!

Upvotes: 4

Views: 2521

Answers (3)

Mina Aziz
Mina Aziz

Reputation: 109

I had the same problem before but in my case, I forgot to populate the object I'm trying to access its id.

Upvotes: 0

Arun AK
Arun AK

Reputation: 4370

I know this is a late answer. But I faced this issue recently and did some search on why the response is given in an Array of Buffer instead of an id. But I couldn't find any resource regarding it.

But, to convert the Buffer into an id. Just use String or toString().

enter image description here

Upvotes: 4

Fullstack Developer
Fullstack Developer

Reputation: 439

In your example, even if the mongoose query behaved as you expected, it would still result in an express server error because you can't call JSON parser. You must have to return the value with JSON parser.

UnitSchema.statics.findByToken = async function (token) {
  const Unit = this
  let unit = await Unit.findOne({ 'Tokens.token': token }).populate('Organisation')
  return JSON.parse(JSON.stringify(unit))
}

Upvotes: -1

Related Questions