Move data from one array to another array in the same document

I have a collection in my database with the data structure shown in the image above. Basically, it is an array of lists and each list has its own array. I’m currently using Node JS along with Mongoose. On the front end this is displayed in the form of a kanban. So the user can move a card from position within the same list, for example, from position 3 to position 0 or can move a card from one list to another, going from list A to list B, and in list B it must be added in position 4 for example, and this object can no longer be present in list A. This is similar to Trello. I want to know how to do this using mongoose. Can someone help me?

Please update your post after reading Formatting code and log snippets in posts.

We need to be able to cut-n-paste your documents to experiment with your issue.

async moveCard(req, res) {
    const { flowID } = req.params;
    const { from, to, fromList, toList } = req.body;

    try {

      const leadsCollection = await Lead.findOne({ flowID });

      if (!leadsCollection) {
        return res.status(404).json({ message: "Erro ao buscar usuário." });
      }
    
      const updatedLeadsList = JSON.parse(JSON.stringify(leadsCollection.leadsList));
      const cardToMove = updatedLeadsList[fromList].cards.splice(from, 1)[0];
      updatedLeadsList[toList].cards.splice(to, 0, cardToMove);
    
      const result = await Lead.findOneAndUpdate(
        { flowID },
        { $set: { leadsList: updatedLeadsList } },
        { new: true }
      );
    
      if (!result) {
        return res.status(404).json({ message: "Erro ao buscar usuário." });
      }

      return res.status(200).json({ message: "Card movido com sucesso."});
    } catch (error) {
      res.status(500).json({ message: "Erro ao mover card." });
    }
  }

Ok, I’m updating here the code snippet I’m using for this problem. As you can see, I’m making a deep copy of leadsList, manipulating it, and then saving the manipulated copy again. As this will be common in the application, I believe it is not viable. I’ll post the data structure I’m working on below here again.

const leadsList = [
  {
    listID: "A",
    cards: [
      {
        id: "card-1",
        createdAt: "",
        variables: []
      },
      {
        id: "card-2",
        createdAt: "",
        variables: []
      }
    ]
  },
  {
    listID: "B",
    cards: [
      {
        id: "card-3",
        createdAt: "",
        variables: []
      },
      {
        id: "card-4",
        createdAt: "",
        variables: []
      }
    ]
  },
]

You could use update with aggregation and use a mixture of $concatArrays and $slice to do the same thing directly on the server.

If you could supply sample documents before and after it would ease finding the right mixture.