简体   繁体   中英

Objects in Meteor Collection

I created the following function to be able to construct objects to store in a Meteor Collection and from there I can access its attributes. The function was created on server side.

  function tweet(uName, sName, uProfile, uTweet, uMedia) {
    this.userName = uName;
    this.screenName = sName;
    this.profileImage = uProfile;
    this.tweet = uTweet;
    this.mediaPic = uMedia;
  }

For testing purposes, I created a random tweet Object :

  var temp = new tweet (john, johnnyBoy, dog, 12, 14);

And when I logged it on console, it has been working fine. For example,

  console.log(temp.userName) //logged john

Now I inserted it into a collection with the following:

  Tweets.insert(temp);

And when I attempted to access the userName, keeps returning undefined.

 console.log(Tweets.find().userName);

Not sure why though.

find returns a cursor. You need to call findOne or fetch (on the cursor) to get a document. For example:

console.log(Tweets.findOne().userName);
console.log(Tweets.find().fetch()[0].userName);

You want to query it like this

console.log(Tweets.findOne().userName);

.find() returns a cursor or a result set. If you want to get an actual item, use .findOne(). Or you could do the following:

console.log(Tweets.find({}, {limit:1}).fetch()[0].userName); // errors out if no tweets in the collection

The function collection.find([selector], [options]) returns a cursor, ie a reactive data source. That means that it does not immediately access the database or return documents. However, cursors provide the functions fetch() , map() and forEach() .

If you want to access a document of your Tweets collection, you need to use Tweets.findOne([selector], [options]) or Tweets.find([selector], [options]).fetch()[0] .

Read more about collection.find([selector], [options]) and collection.findOne([selector], [options]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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