compare-objectId.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import mongoose from 'mongoose';
  2. type IObjectId = mongoose.Types.ObjectId;
  3. const ObjectId = mongoose.Types.ObjectId;
  4. export const isIncludesObjectId = (arr: (IObjectId | string)[], id: IObjectId | string): boolean => {
  5. const _arr = arr.map(i => i.toString());
  6. const _id = id.toString();
  7. return _arr.includes(_id);
  8. };
  9. /**
  10. * Exclude ObjectIds which exist in testIds from targetIds
  11. * @param targetIds Array of mongoose.Types.ObjectId
  12. * @param testIds Array of mongoose.Types.ObjectId
  13. * @returns Array of mongoose.Types.ObjectId
  14. */
  15. export const excludeTestIdsFromTargetIds = <T extends { toString: any } = IObjectId>(
  16. targetIds: T[], testIds: (IObjectId | string)[],
  17. ): T[] => {
  18. // cast to string
  19. const arr1 = targetIds.map(e => e.toString());
  20. const arr2 = testIds.map(e => e.toString());
  21. // filter
  22. const excluded = arr1.filter(e => !arr2.includes(e));
  23. // cast to ObjectId
  24. const shouldReturnString = (arr: any[]): arr is string[] => {
  25. return typeof arr[0] === 'string';
  26. };
  27. return shouldReturnString(targetIds) ? excluded : excluded.map(e => new ObjectId(e));
  28. };
  29. export const removeDuplicates = (objectIds: (IObjectId | string)[]): IObjectId[] => {
  30. // cast to string
  31. const strs = objectIds.map(id => id.toString());
  32. const uniqueArr = Array.from(new Set(strs));
  33. // cast to ObjectId
  34. return uniqueArr.map(str => new ObjectId(str));
  35. };