Home > Net >  Mongodb empty object Object.keys(myObj).length return wrong values
Mongodb empty object Object.keys(myObj).length return wrong values

Time:11-10

I have an object inside collection called "childLimit". Schema: user: { name: {type: String}, childLimit: {dailyLimit: {type: Number} }

Now if I haven't inset any info in this object (childLimit) while creating user so it should not be there as mongo work, that fine. but when I console this it return {} empty object which is fine. But when I console.log(Object.values(childLimit)) it console [ true, undefined, undefined, undefined ] which is strange???? Object.keys(childLimit).length return 2 but it should be 0??

Now how can I check if the object is empty?? OR if the object exist??

CodePudding user response:

This seems to be about Mongoose, am I right?

Just log the keys which you count, and you will see something like follows: Mongoose-internal properties, but not your document's keys:

console.log(Object.keys(doc));
// [ '$__', 'isNew', 'errors', '$locals', '$op', '_doc' ]

What you actually want are the properties of the document. You can do this as follows:

console.log(Object.keys(doc.toObject()));
// [ 'foo', 'bar', 'baz' ]

Or alternatively (this doesn't seem to be a public API though!):

console.log(Object.keys(doc._doc));
// [ 'foo', 'bar', 'baz' ]

Note that sometimes, both can return different results.

  • Related