compare-objectId.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import mongoose from 'mongoose';
  2. import { ObjectIdLike } from '~/server/interfaces/mongoose-utils';
  3. type IObjectId = mongoose.Types.ObjectId;
  4. const ObjectId = mongoose.Types.ObjectId;
  5. export const isIncludesObjectId = (arr: ObjectIdLike[], id: ObjectIdLike): 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: ObjectIdLike[],
  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. };