Meteor cursor.map():GOTCHA如何多次提取一个元素?

cho*_*man 3 javascript cursor meteor

如何将地图功能用于流星集合?

http://docs.meteor.com/#map

使用教程,我们有一个名为Posts的集合.

Posts.find()返回一个游标,让我遍历所有Posts.find().fetch()会给我一个包含所有帖子的数组,但这可能是很多数据.

假设我只想在一个数组中使用Posts的一个元素,比如标题:我可以这样做:

titles=Posts.find().map(function(a) {return a.title}); // works
Run Code Online (Sandbox Code Playgroud)

假设我想要标题和ownerIds.我正在调试这个并做了:

a=Posts.find()
titles=a.map((function(a) {return a.title;}); // works
ownerIds=a.map((function(a) {return a.ownerId;}); //doesn't work, cursor already iterated over, returns empty array.
Run Code Online (Sandbox Code Playgroud)

这不起作用.为什么?

Dav*_*don 10

您可以通过在其上调用rewind来多次使用游标.来自文档:

forEach,map或fetch方法只能在游标上调用一次.要多次访问游标中的数据,请使用快退重置光标.

所以这应该工作:

a=Posts.find()
titles=a.map((function(a) {return a.title;});
a.rewind();
ownerIds=a.map((function(a) {return a.ownerId;});
Run Code Online (Sandbox Code Playgroud)