delete all objects in find function mongodb

Viewed 35

So whenever I create a server it creates two categories and 1 channel for said category. The problem is when I try to delete a server I want to delete all the categories and channels related to that server. Can anyone tell me how to do that?

Here is what i've tried so far

controllers/servers.js

module.exports.deleteServer = async (req, res) => {
  try {
    const server = await Server.findById(req.params.id);

    const categories = await Category.find({ serverId: server._id });
    const channels = await Channel.find({ categoryId: categories._id });

    // security validation
    if (server?.ownerId !== req?.user?._id)
      return res?.status(403).json("You are not the owner!");

    await categories.deleteMany()
    await channels.deleteMany()

    await server.deleteOne();

    res?.json("Server successfully deleted!");
  } catch (error) {
    res?.status(500).json({ error: error?.message });
  }
};

When I use the deleteMany method it gives me an error saying it is not a function and if I use the deleteOne method it only deletes one of the items not all of them.

Does anyone know how to solve this?

1 Answers

You should use Delete All Documents that Match a Condition method to do it.

module.exports.deleteServer = async (req, res) => {
    try {
        const serverId = req.params.id;
        const server = await Server.findById(serverId);
        if (!server) {
            res?.status(500).json({ error: 'No server found' });
        }
        // security validation
        if (server?.ownerId !== req?.user?._id) {
            return res?.status(403).json("You are not the owner!");
        }

        const categoryIds = await Category
            .find({ serverId: server._id })
            .toArray()
            .map((category) => category._id);

        // Delete all channels
        await channels.deleteMany({ categoryId: categoryIds });

        // Delete all categories
        await categories.deleteMany({ serverId });

        // Delete server
        await server.deleteOne({ _id: serverId });

        res?.json("Server successfully deleted!");
    } catch (error) {
        res?.status(500).json({ error: error?.message });
    }
};

Related