compare-objectId.ts 1.4 KB

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