Mr_E
Mr_E

Reputation: 709

Strange characters for _id field when doing mongoose aggregate query

I am running a query to try and get a count of duplicate id records.

"song" is a subdocument which contains just an _id field in the database. After I run the query I am getting these strange characters in my console output, how come I am not able to get the actual id string that looks like, "555699e4ab3e43ec12accaf9"?

console

Upvotes: 1

Views: 983

Answers (1)

laggingreflex
laggingreflex

Reputation: 34667

Those characters are the 12 byte id binary string. And it's actually _id.id i.e. id property on the _id object which is an ObjectID. Your 24 byte binary "555.." is _id itself, which converts to string automatically if you use it as one.


* more details on how object can be represented as a string: Object.prototype.toString()

Unfortunately for you, whatever IDE you're using is showing it as an object (which is actually what it really is).

Try console.log(util.inspect(results)) (be sure to require the util module)


In any case, console.log(result[0]._id) will give you the 24 byte hex string "5556...ccaf9".

If you don't want the _id which is an object, there's also a getter id which is a String by default.

console.log(typeof result[0]._id) //=> "object"
console.log(typeof result[0].id) //=> "string"

Upvotes: 3

Related Questions