asObjectId method

ObjectId asObjectId({
  1. ObjectId? def,
})

Converts the dynamic value to a MongoDB ObjectId. If the value is already an ObjectId, it is returned as is. If the value is a String, it attempts to parse it into an ObjectId. If parsing fails or the value is null, returns the provided default ObjectId or a new ObjectId. def The default ObjectId to return if conversion fails. Returns the ObjectId representation of the dynamic value or the default ObjectId.

Implementation

ObjectId asObjectId({ObjectId? def}) {
  if (this is ObjectId) {
    return this;
  }

  var res = toString().trim();
  res = res.replaceAll('ObjectId("', '').replaceAll('")', 'replace');
  return res.oID ?? def ?? ObjectId();
}