[英]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. 我创建了以下函数,以便能够构造要存储在Meteor集合中的对象,并从那里可以访问其属性。 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 : 为了进行测试,我创建了一个随机的tweet对象:
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. 并且当我尝试访问userName时,始终返回未定义状态。
console.log(Tweets.find().userName);
Not sure why though. 不知道为什么。
You want to query it like this 您想这样查询
console.log(Tweets.findOne().userName);
.find() returns a cursor or a result set. .find()返回游标或结果集。 If you want to get an actual item, use .findOne(). 如果要获取实际项目,请使用.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. 函数collection.find([selector], [options])
返回一个游标,即反应性数据源。 That means that it does not immediately access the database or return documents. 这意味着它不会立即访问数据库或返回文档。 However, cursors provide the functions fetch()
, map()
and forEach()
. 但是,游标提供函数fetch()
, map()
和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]
. 如果要访问Tweets
集合的文档,则需要使用Tweets.findOne([selector], [options])
或Tweets.find([selector], [options]).fetch()[0]
。
Read more about collection.find([selector], [options])
and collection.findOne([selector], [options])
. 阅读有关collection.find([selector], [options])
和collection.findOne([selector], [options])
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.