tanutapi / dart_meteor

A Meteor DDP library for Dart/Flutter developers.
Other
37 stars 15 forks source link

Get custom fields from user #38

Closed keepjhonnying closed 3 years ago

keepjhonnying commented 3 years ago

Hi.

How to get custom fields from user?

Is through user method?

https://pub.dev/documentation/dart_meteor/latest/dart_meteor/MeteorClient/user.html

tanutapi commented 3 years ago

Are you using Flutter? In an example, you can see how to use the user() stream.

https://github.com/tanutapi/dart_meteor/blob/c76b64e3bd5cac71c9e48a79922711392fea6339/example/lib/main.dart#L90-L100

To access a custom field, you can do something like: snapshot.data['customField'].

Or if you don't want to wait for the stream, you can use meteor. userCurrentValue() which returns the Map<String, dynamic> directly.

keepjhonnying commented 3 years ago

Thanks for the reply @tanutapi

Yes. I'm using Flutter.

In the code:

        StreamBuilder(
          stream: meteor.user(),
          builder: (context, snapshot) {
            var a = snapshot.data as Map;
            return Text(a['username'].toString());
          },

        ),

return Text(a['username'].toString()); return the username

but if i change to

return Text(a['customfield'].toString());

return null

And if

print(a.toString());

I see only default fields and fields under profile Edit: Same result with meteor.userCurrentValue()

{
username: myusername,
emails: [{address:
email@gmail.com, verified: false}],
profile: {fullName: Long Full Name},
_id: oGijmwaxqaX9DwT5j
}
keepjhonnying commented 3 years ago

By default the accounts package only publishes the id, username and profile fields. To publish more, add this 'universal' publish to the server:

Meteor.publish(null, function() {

  if (this.userId != null) {
    return Meteor.users.find({
      _id: this.userId
    }, {
      fields: {
        'customfield': 1,
      }
    });
  } else {
    return this.ready();
  }
});

Source: https://stackoverflow.com/a/28514642/3259363

After add this, show the custom field.

Sorry for taking your time and thanks for your attention.

tanutapi commented 3 years ago

Yes, that's the Meteor's behavior. Also, you may want to add a deny permission on user's profile object since by default the client allows to update their own profile. Ref: https://guide.meteor.com/accounts.html#dont-use-profile

If you plan to store some important information inside the profile, you must:

// Deny all client-side updates to user documents
Meteor.users.deny({
  update() { return true; }
});

Best,