Can not get user by objectId Moralis.User [SOLVED]

The user is undefined when I run this code. What is wrong with it?

Moralis.Cloud.define("getUser", async (request) => {
  	const User = Moralis.Object.extend("User");
	const query = new Moralis.Query(User);
  	query.equalTo("objectId", request.user.id);
  	const user = await query.first();
  	return user;
});
1 Like

Hey @metylbk

User objects are prottected by CLP. You need to add useMasterKey: true for getting info from protected fields

const user = await query.first({ useMasterKey: true })

Where do you run the code from? From your front-end with an authorized user or from Moralis Api Console?

I run in cloud function on Moralis server.

Could you share the command you use to run the cloud code?

Sorry, this function I wrote in the cloud.
and in the front-end, I call:
const user = await Moralis.Cloud.run(“getUser”);

request.user.id will work for you only if you call it from the frontend with authorised user

request.user.id => this one is in cloud function, it’s ok, I already tested.
When I call:
const user = await query.first({ useMasterKey: true })
it returns user but not full information, because in the user table, I have some custom fields.

Why don’t you use this method directly from the front end?

const user = Moralis.User.current();
console.log(user.attributes)

Because I have more fields in user table, but when user Moralis.User.current() it not show the custom fields.

It will return you User object:

{
  className: "_User"
  id: String
  _objCount: 0
  attributes: {
    accounts: Array,
    ACL: Object,
    authData: Object,
    createdAt: Date,
    email: String, // empty
    ethAddress: String,
    sessionToken: String, 
    updatedAT: Date,
    username: String, // random value
  }
}

And after specifying user.attributes you will get all your filelds from the database

const user = Moralis.User.current();
console.log(user.attributes)

it’s ok now.
The solution is we get user from cloud function, and console.log(user.attributes).
If use Moralis.User.current(); it will not work for showing custom fields.
Thank you

1 Like

user.get("column_name") - do this and tell me how it works

Actually Moralis.User.current() shows custom fields

I guess the problem was in that you have added new fields after you have logged in. So, you have used old User object. You can update your user object by:

let user = await Moralis.User.current().fetch();

Yes you are right. I forgot to logout user after changing the database, so that’s why I didn’t see the new custom fields.
Thank Ivan and Yomoo.

1 Like