parts and areas tested

This commit is contained in:
2025-11-24 21:04:14 +03:00
parent a5a7a7e7b5
commit eedfed1a65
131 changed files with 5429 additions and 471 deletions

View File

@@ -0,0 +1,25 @@
import { Types, Model } from "mongoose";
type ObjectIdLike = Types.ObjectId | string;
interface CleanRefArrayParams {
parentModel: Model<any>;
refModel: Model<any>;
parentId: ObjectIdLike;
fieldName: string;
}
export async function cleanRefArrayField({ parentModel, refModel, parentId, fieldName }: CleanRefArrayParams): Promise<{ keptIds: Types.ObjectId[]; removedIds: Types.ObjectId[] }> {
const parent = await parentModel.findById(parentId).lean();
if (!parent) { throw new Error("Parent document not found") }
const rawIds: ObjectIdLike[] = parent[fieldName] || [];
if (!Array.isArray(rawIds) || rawIds.length === 0) { return { keptIds: [], removedIds: [] } }
const ids = rawIds.map((id) => typeof id === "string" ? new Types.ObjectId(id) : id);
const existing = await refModel.find({ _id: { $in: ids } }).select("_id").lean();
const existingSet = new Set(existing.map((d) => String(d._id)));
const keptIds = ids.filter((id) => existingSet.has(String(id)));
const removedIds = ids.filter((id) => !existingSet.has(String(id)));
await parentModel.updateOne({ _id: parentId }, { $set: { [fieldName]: keptIds } });
return { keptIds, removedIds };
}