2015-05-25 137 views
0

你好,我剛剛創建骨架流星JS應用程序獲取從MongoDB的數據並寫入主js文件下面的代碼:如何流星JS

People = new Meteor.Collection("people"); 

People.insert({name: 'test'}); 
console.log(People.find().fetch()); 

我重新加載頁面和記錄插入MongoDB中,我看到它在mongodb命令行但當我嘗試從數據庫獲取結果接收空數組?

回答

1

收集方法異步:這基本上意味着他們停止進程,直到他們完成。因此,對於您的情況,您正試圖獲取之前插入的人,而無需等待所述插入結束。

這就是爲什麼Collection.insert可以使用一個可選回調函數作爲參數,將盡快插入結束叫做:

People = new Meteor.Collection("people"); 

People.insert({name: 'test'}, function() { 
    // this will be printed after the insert is done 
    console.log(People.find().fetch()); 
}); 
// this will be printed after the insert is started, and (probably) before it is finished. 
console.log('Insertion started!');