Real Madrid battled back from behind to beat city neighbours Leganes 3-2 at the Santiago Bernabeu, with Kylian Mbappe scoring the first free-kick of his career.