An independent attorney is often hired to prepare the deed and other legal papers. The title company reviews the history of the property and alerts you to any potential problems. If the title company discovers a substantial problem with the seller's ownership, they will refuse to issue a title policy. In your case, they would have found that your seller had not yet paid off his existing mortgage. You could have then made financial arrangements to satisfy his mortgage company.
Foreclosure happens when a lien holder's rights are violated.
You lose the house due to the seller's fraud. Whenever you are purchasing real property you should have a title insurance policy. If you had a policy, the insurance company could have kept you out of this mess in the first place. If they had missed a problem, they would defend you and possibly refund the money you lost. The answer may or may not match your individual situation.