His margin of fewer than 5,000 votes caps a midterm wave that has handed Democrats control of both chambers of Congress.