Hi @copleykj,
inside a publication do you mean it like this? https://galaxy-guide.meteor.com/apm-improve-cpu-and-network-usage.html#Always-Do-a-Null-Check-for-id
I think this.userId will not work on a server side method (method called by the server, on the server) or pretty much anywhere on the client.
Server only method - no access to a user Id via ‘this’.
Server defined, client called method: use ‘this.userId’ within the method.
Client - use Meteor.userId()
@morningstardev13 the function as you describe can use this.userId (not this.userId()) if you include it in a method accessible both on the server and client.
Let’s say you have a file called ‘methods.js’. You write your method, and import this file on both server and client startup.
example:
Server:
import { Meteor } from 'meteor/meteor'
import { ValidatedMethod } from 'meteor/mdg:validated-method'
import SimpleSchema from 'simpl-schema'
export const yourMethodName = new ValidatedMethod({
name: 'yourMethodName',
validate: new SimpleSchema({
some value to validate if any: String, ...
}).validator(),
run ({ values if any }) {
if (Meteor.isServer) {
if (!this.userId) { throw new Meteor.Error('not-authorized') } // you are on the server here
return Meteor.users.findOne({ _id: this.userId }, { fields: { “recruiterId”: 1 } })
// or return Meteor.users.find({ _id: this.userId }, { recruiterId: { $exists: true } } }).count() (add limit: 1 just in case but on the _id should not be necessary). This is when you want to return count 1 if exists or 0 if it doesn't exists if you are forced to use a boolean as a return of the method.
}
}
})
On client:
Meteor.call(‘yourMethodName’, { values if any or empty }, (err, res) => {…handle both err and res })
So this was for ‘this.userId’
Otherwise, at any point on the client you can use:
let a = Meteor.users.findOne({_id: Meteor.userId()}, {fields: {“recruiterId”: 1} }); // get an object { _id: ..., recruiterId: .... }
// but Meteor.users.findOne({_id: Meteor.userId()}) = Meteor.user() as long as you have a publication for the necessary fields
let a = Meteor.user().recruitertId // get a string or number or undefined
// or with a guard if no user is logged in.
const user = Meteor.user()
let a = user && user.recruiterId . // or Meteor.user() && Meteor.user().recruiterId