Lets say a document is :
{
a: 1,
b: 1,
c: 2,
....
z: 2
}
How can I count the number of keys in such document?
Thank you
If You are work with Documents like the mongoose.Document, You can try to count all keys inside the doc after transform in a object, 'cause, before it, the doc just have commom properties:
Object.keys(document); // returns [ '$__', 'isNew', 'errors', '_doc', '$locals' ]
Object.keys(document).length; // returns ALWAYS 5
So, try cast to an object, after pass it to Object.keys
console.dir(
Object.keys(document.toObject()) // Returns ['prop1', 'prop2', 'prop3']
);
And to show the keys count
console.log(
Object.keys(document.toObject().length)
); // Returns 3
And Be Happy!!!