Preheat the oven to 350°F (175°C). Lightly grease a 9x13-inch baking dish.
Cook the spaghetti in a large pot of salted boiling water according to package directions until al dente; drain and set aside.
While pasta cooks, heat olive oil in a large skillet over medium heat. Add chopped onion and cook until softened, about 4–5 minutes.
Add minced garlic and cook 30 seconds until fragrant, then add ground beef and cook, breaking up with a spoon, until no longer pink.
Stir in tomato sauce, oregano, basil, salt, and pepper. Simmer the sauce 5–10 minutes to blend flavors, then remove from heat.
In a large bowl, combine the drained spaghetti, meat sauce, beaten eggs, half of the shredded mozzarella, and half of the parmesan (if using). Mix until evenly combined.
Transfer the mixture to the prepared baking dish and spread evenly. Sprinkle the remaining mozzarella and parmesan over the top.
Bake uncovered for 20 minutes, or until cheese is melted and bubbly and edges are lightly browned. Let rest 5 minutes before serving.