简体   繁体   中英

Meteor how to retrieve the value of an attribute of a collection object

I have the Meteor.users collection. users have an attribute called “lastQuestionAnswered”, which is the questionId of the last question that the user has answered.

{ "_id" : "jrCJiuo7eprNFKfLG",
"name" : "Elon Musk",
"lastQuestionAnswered" : 1 }

How do I extract the value of the lastQuestionAnswered attribute (of the current user) into a variable? So that in the end we have

Var lastAnsweredQuestionId = ???

I am trying to do this server-side. I have looked at related questions but could not find any hints. Thanks in advance for your help.

In order to get current user on client side you need to use Meteor.user() method. So your code will look like:

var lastAnsweredQuestionId = Meteor.user().lastQuestionAnswered;

It will work on client side or in methods on server side (if user is logged in).

UPDATE

If you need to get same result in publish function you need a bit different approach because Meteor.user() doesn't work in publishers:

var currentUser = Meteor.users.findOne({_id: this.userId});
var lastAnsweredQuestionId = currentUser.lastQuestionAnswered;

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