Meteor: how do I return data from fields in a specific object?

流过昼夜 提交于 2019-12-23 02:30:57

问题


This should be a fairly simple one.

myobject has various properties, _id, name, createdBy, date etc

In my find query I want to only return specific fields from within myObject. So for example, what would I need to do to modify the find query below so that only name was returned?

myCollection.find({createdBy: someId}, {fields: {myObject: 1}}).fetch();

Currently this will return everything in myObject which it should do, I just want one field within myObject returned.


回答1:


Here is a way to do it within the query:

myCollection.find({createdBy: someId}, {fields: {'myObject.name': 1}}).fetch();

Note the quotes around

'myObject.name'




回答2:


Lets assume we are talking about posts, and a post document looks like this:

{
  _id: 'abc123',
  title: 'All about meteor',
  author: {
    firstName: 'David',
    lastName: 'Weldon'
  }
}

You can then extract all of the last names from all of the authors with this:

var lastNames = Posts.find().map(function(post) {
  return post.author.lastName;
});

Modify the selector and options as needed for your collection. Using fields in this case may be a small optimization if you are running this on the server and fetching the data directly from the DB.



来源:https://stackoverflow.com/questions/26081154/meteor-how-do-i-return-data-from-fields-in-a-specific-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!