Object.keys() returns unexpected keys on MongoDB object from collection [duplicate]
Solution 1:
for ... in
iterates all enumerable properties, both own and inherited. This is not "a strange bug," this is in fact the intended behavior.
As for the Object.keys()
, unless it was overwritten by a non-compliant implementation, those are in fact enumerable keys of the object itself, so you are most likely mistaken. The e
object has a .toJSON()
method in its prototype that is implicitly called when you do console.log(e)
, so that is probably the output you are seeing there, and is not likely going to reflect exactly the same property keys as the original object. Try calling console.log(e.toJSON())
and I'm guessing it will be the same output as in the first one.
If you want only the object's own properties, use Object.getOwnPropertyNames(e)
.
If you want the keys printed in the first output, then use Object.keys(e.toJSON())
.