Magnesium (group IIA) loses two electrons to become a cation. This is the most energetically favorable way for Magnesium to obtain a valence electron that is stable (octet). When an atom loses electrons it has a positive charge that matches the number of electrons lost.
Nitrogen (group VA) gains three electrons to become an anion. This is the most energetically favorable way for Nitrogen to obtain a valence electron that is stable (octet). When an atom gains electrons it has a negative charge that matches the number of electrons gained.