Vainsteins sprinted from a small group about a kilometer from the finish and nipped Poland's Zbigniew Spruch for the win.
He finished the 269-kilometer race in 6 hours, 19 minutes and 20 seconds.
For Vainsteins, who turned professional only two years ago, it was the biggest win of his career.
As he accepted the medal and the Latvian flag was flown, Vainsteins broke into tears.
"I'm going to savor this victory, it's not every day you're world champion," he told reporters afterward.
His road to the world championship title was not smooth. Vainsteins' father died of cancer last spring in his hometown of Kuldiga, and Latvian sports fans and journalists castigated him for his decision to forego the Olympic Games in Sydney to concentrate on the World Championship.
"He needed to achieve something at the world championships to change the attitude of the Latvian nation," said Arturs Vaiders, sports editor for Diena. "He needed a medal and he knew it."
Vainsteins spends most of his time outside of Latvia, training in Italy. When he opted out of the Olympics, many Latvians cried treason.
"Everybody said, 'What are you doing, the Olympics are the main goal for us,'" said Janis Pinkulis, a writer for the sports weekly Sporta Avize.
Vainsteins had previous run-ins with Latvia's Olympic Committee. He was reportedly refused funding in 1996 to train in a country where cyclists are considered more of a nuisance than athletes.
"He was a prospective athlete, but there are a lot of them," said Pinkulis.
Vainsteins made a name for himself in European road racing in recent years and hooked up with a well-funded Italian team. He made minor waves when he won a stage in the Giro Italia, the world's second most famous road race behind the Tour de France. He continued that success with several top-10 finishes in this year's Tour de France.