Why does lodash consider a mongoose object id as empty when it did not before?

23 Views Asked by At

Example would be:

const objectId = new mongoose.Types.ObjectId('id would go here');
  if (_.isEmpty(objectId)) {
    throw new Error('this throws an error');
  }

ran code above and was just wondering if this is new, for what its worth, this code did not break before.

1

There are 1 best solutions below

0
Vivick On

Using the following code:

const _ = require("lodash");
const mongoose = require("mongoose");

const objectId = new mongoose.Types.ObjectId('deadcaffee00deadbeef1122');

const isEmpty = _.isEmpty(objectId);

console.log("keys", Object.keys(objectId));
for (let i in objectId) {
    console.log("property", i, objectId[i]);
}

console.log({ objectId, isEmpty });

You can see that objectId only contains one property that whose key is a Symbol.

You'll note that it isn't logged as a property (only valueOf is logged), and that the keys array is empty.

Looking at the source code you'll see it iterates over the keys using a for-in loop just as I did to log the properties.

Since we have no properties to log that satisfies hasOwnProperty, then the loop ends and it returns true.