Prior to migration, there were two pledges of Allegiance between The Ansar, and the Messenger of Allah (saw).
The first meeting with the Ansar, was when the Messenger (saw) went out in the Hajj season. According to reliable sources, there were six people from Al Khazraj who met with the Prophet (saw) and embraced Islam. When the returned to Madinah, they told their people about the messenger of Allah (saw), so that the following year, there were twelve men from Ansar who pledged their allegiance to the Messenger (saw). This was known as the first pledge of Allegiance at Al Aqabah. The second pledge however, took place approximately ten years later, again during the hajj season. Seventy men pledged allegiance to him (saw).
So by Allah’s will, there was already a large number of Muslims in Madinah by the time the Messenger (saw) was commanded by Allah to migrate. Allah (swa) says in the Qur’an: “And say (Oh Muhammad): My Lord! Let my entry (to the city of Madinah) be good, and (likewise) my exit (from Makkah) be good.” [Al Israa 17:80]
When the Quraish saw that many Muslims were migrating to Madinah, they devised a plot to kill Muhammad (saw), but Allah (swa) is a better plotter, and informed the Messenger (saw) of their evil plot, and thus ordered him to migrate that very night. The Messenger (saw) chose Abu Bakr to be his companion.
When the people of Madinah heard that their believer Messenger had left Makkah, they use to wait from morning till dusk, anticipating their arrival. They arrived on Monday, the 12th of Rabi’ul Awwal, in the thirteenth year of his prophethood.
Anas (ra) said: “I never saw a brighter day than the day on which Allah’s Messenger (saw) and Abu Bakr (ra) entered Madinah.” [Ahmad]
The popel of Madinah rejoiced and celebrated at his (saw) arrival. Al Bara (ra) said: “I had not seen the people of Madinah celebrate anything as they celebrated the arrival of Allah’s messenger (saw).” [al Bukhary]
According to Bukhary and Muslim, the Messenger of Allah (saw) stayed in Quba for fourteen nights, and during this time, he (saw) built Masjid Quba.