File size: 886 Bytes
81fc505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Card } from "../models/Card.js";
import { Entry } from "../models/Entry.js";
export async function getDescendantCardIds(rootId) {
  const cards = await Card.find({}, { _id: 1, parentId: 1 }).lean();
  const childrenMap = new Map();
  cards.forEach((card) => {
    const key = String(card.parentId || "");
    const current = childrenMap.get(key) || [];
    current.push(String(card._id));
    childrenMap.set(key, current);
  });
  const result = [];
  const stack = [String(rootId)];
  while (stack.length > 0) {
    const nextId = stack.pop();
    result.push(nextId);
    const children = childrenMap.get(nextId) || [];
    stack.push(...children);
  }
  return result;
}
export async function deleteCardCascade(cardId) {
  const ids = await getDescendantCardIds(cardId);
  await Entry.deleteMany({ cardId: { $in: ids } });
  await Card.deleteMany({ _id: { $in: ids } });
}