| 1618 | } |
| 1619 | |
| 1620 | public static async deleteTeam({ teamId, userId }) { |
| 1621 | if (!userId || !teamId) { |
| 1622 | throw new Error('Bad data.'); |
| 1623 | } |
| 1624 | |
| 1625 | // remove all Discussions and Comments |
| 1626 | const discussionsOfTeam = await Discussion.find({ teamId }).setOptions({ |
| 1627 | lean: true, |
| 1628 | }); |
| 1629 | |
| 1630 | for (const discussion of discussionsOfTeam) { |
| 1631 | const discussionId = discussion._id.toString(); |
| 1632 | |
| 1633 | const commentsToBeRemoved = await Comment.find({ |
| 1634 | discussionId, |
| 1635 | }).setOptions({ lean: true }); |
| 1636 | |
| 1637 | const commentIdsToBeRemoved = commentsToBeRemoved.map((c) => { |
| 1638 | return c['_id'].toString(); |
| 1639 | }); |
| 1640 | |
| 1641 | // remove all comments and files if any |
| 1642 | for (const commentId of commentIdsToBeRemoved) { |
| 1643 | await Comment.delete({ userId, id: commentId, isDiscussionBeingDeleted: true }); |
| 1644 | } |
| 1645 | |
| 1646 | await Discussion.deleteOne({ _id: discussionId }); |
| 1647 | } |
| 1648 | |
| 1649 | // remove all Chats and Messages |
| 1650 | const chatsOfTeam = await Chat.find({ teamId }).setOptions({ |
| 1651 | lean: true, |
| 1652 | }); |
| 1653 | |
| 1654 | for (const chat of chatsOfTeam) { |
| 1655 | const chatId = chat._id.toString(); |
| 1656 | |
| 1657 | const messagesToBeRemoved = await Message.find({ |
| 1658 | chatId, |
| 1659 | }).setOptions({ lean: true }); |
| 1660 | |
| 1661 | const messageIdsToBeRemoved = messagesToBeRemoved.map((m) => { |
| 1662 | return m['_id'].toString(); |
| 1663 | }); |
| 1664 | |
| 1665 | // remove all comments and files if any |
| 1666 | for (const messageId of messageIdsToBeRemoved) { |
| 1667 | await Message.delete({ userId, id: messageId }); |
| 1668 | } |
| 1669 | |
| 1670 | await Chat.deleteOne({ _id: chatId }); |
| 1671 | } |
| 1672 | |
| 1673 | const teamLeader = await this.findById(userId).setOptions({ lean: true }); |
| 1674 | |
| 1675 | const teamToBeDeleted = teamLeader.teamsForTeamLeader.find((team) => { |
| 1676 | return team.teamId === teamId; |
| 1677 | }); |