2015-05-25 105 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!');