compare-objectId.ts 1.5 KB

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