objectid-utils.ts 437 B

12345678910111213141516
  1. import ObjectId from 'bson-objectid';
  2. export function isValidObjectId(
  3. id: string | ObjectId | null | undefined,
  4. ): boolean {
  5. if (id == null) {
  6. return false;
  7. }
  8. // implement according to https://www.geeksforgeeks.org/how-to-check-if-a-string-is-valid-mongodb-objectid-in-node-js/
  9. if (typeof id === 'string') {
  10. return ObjectId.isValid(id) && new ObjectId(id).toHexString() === id;
  11. }
  12. return ObjectId.isValid(id);
  13. }