janjackson
janjackson

Reputation: 351

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.

Upvotes: 3

Views: 376

Answers (1)

LazyCat01
LazyCat01

Reputation: 1049

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;

Upvotes: 2

Related Questions