简体   繁体   English

如何在javascript(meteor.js)中操作返回的mongo集合/游标?

[英]how to manipulate returned mongo collections / cursors in javascript (meteor.js)?

In working with Meteor.js and Mongo I use the find({ some arguments }) and sometimes find({ some arguments }).fetch() to return cursors and an array of matching documents respectively. 在使用Meteor.js和Mongo时,我使用find({ some arguments }),有时会找到({ some arguments })。fetch()分别返回游标和匹配文档数组。

What is the real difference between the two? 这两者之间真正的区别是什么? (when would I use one versus the other?) (我什么时候才能使用其中一个?)

What is the proper way to manipulate/iterate over these type of returned objects? 操作/迭代这些类型的返回对象的正确方法是什么?

Eg I have a collection that has many documents each with a title field. 例如,我有一个包含许多文档的集合,每个文档都有一个标题字段。

My goal was to get an array of all the title fields' values eg [doc1title,doc2title,doc3title] 我的目标是获得所有标题字段值的数组,例如[doc1title,doc2title,doc3title]

I did this: 我这样做了:

var i, listTitles, names, _i, _len;
names = Entries.find({}).fetch();
listTitles = [];
for (_i = 0, _len = names.length; _i < _len; _i++) {
    i = names[_i];
    listTitles.push(i.title);
}

or the equivalent in coffeescript 或等同于coffeescript

names = Entries.find({}).fetch()
listTitles = []
for i in names
    listTitles.push(i.title)

which works, but I have no idea if its the proper way or even a semi sane way. 这是有效的,但我不知道它是正确的方式,甚至是半合理的方式。

Your first question has been asked before - also see this post. 之前已经问你的第一个问题 - 也看到这篇文章。 The short answer is that you want to use the cursor returned by find unless you really need all of the data at once in order to manipulate it before sending it to a template. 简短的回答是你想要使用find返回的光标,除非你真的需要所有的数据,以便在将它发送到模板之前对其进行操作。

Your CoffeeScript could be rewritten as: 您的CoffeeScript可以重写为:

titles = (entry.title for entry in Entries.find().fetch())

If you are using underscore, it could also be written as: 如果您使用下划线,它也可以写成:

titles = _.pluck Entries.find().fetch(), 'title'

To iterate over a cursor in js simply use cursor.forEach 要在js中迭代游标,只需使用cursor.forEach

const cursor = Collection.find();
cursor.forEach(function(doc){
  console.log(doc._id);
});

When converting cursors to arrays you will also find the .map() function useful: 将游标转换为数组时,您还会发现.map()函数很有用:

const names = Entries.find();
let listTitles = names.map(doc => { return doc.title });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM