Exposure to even trace amounts of Cd(II) and Pb(II) in food can have serious effects on the human body. Therefore, the development of novel electrochemical sensors that can accurately detect the different toxicity levels of heavy metal ions in food is of great significance. Based on the principle of green chemistry, we propose a new type of boron and nitrogen co-doped carbon (BCN) material derived from a metal-organic framework material and study its synthesis, characterization, and heavy-metal ion detection ability. Under the optimum conditions, the BCN-modified glassy carbon electrode was studied using square-wave anodic stripping voltammetry, which showed good electrochemical responses to Cd(II) and Pb(II), with sensitivities as low as 0.459 and 0.509 μA/μM cm2, respectively. The sensor was successfully used to detect Cd(II) and Pb(II) in Beta vulgaris var. cicla L samples, which is consistent with the results obtained using inductively coupled plasma-mass spectrometry. It also has a strong selectivity for complex samples. This study provides a novel approach for the detection of heavy metal ions in food and greatly expands the application of heteroatom-doped metal-free carbon materials in detection platforms.