如何在流星js中从mongodb获取数据

时间:2015-05-25 23:41:32

标签: meteor

您好我只需创建骨架meteor js应用程序并在主js文件中编写以下代码:

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

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

我重新加载页面并在mongodb中插入记录,我在mongodb命令行中看到它,但是当我尝试从数据库中获取结果时接收空数组?

1 个答案:

答案 0 :(得分: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!');