Meteor-Community-Packages / meteor-collection2

A Meteor package that extends Mongo.Collection to provide support for specifying a schema and then validating against that schema when inserting and updating.
https://packosphere.com/aldeed/collection2
MIT License
1.02k stars 108 forks source link

Update User Profile (the right way) #331

Closed odesey closed 6 years ago

odesey commented 8 years ago

I am trying to determine if there is is a better way to validate and update a user profile using Simple Schema and Collection2 packages (no autoform).

On the user creation method I call: Schemas.Users.clean(user) and check(user, Schemas.User) on the server side to validate the user object before insertion. Works great, and all fields are properly validated.

Problem is on the update. I only need to validate the fields in the user's profile. So calling clean() and check() on the object passed, fails as it only includes fields from the user.profile. This leads to another issue, when I call:

Meteor.users.update(Meteor.userId(), {$set: {profile: user.profile}})

to update the users profile with the new data, none of the fields in the user.profile object are validated. Blank fields are even inserted even when I set optional to false like so:

'profile.lastName': {
  type: String,
  optional: false,
  label: 'The last name of the user.'
},

So as a workaround to this, I first grab the user from the DB doing a

const updateUser = Meteor.users.find()

and replace the updateUser.profile object with the one passed from the server like so:

updateUser.profile = user.profile

Finally I call my clean and check against the updateUser object and finally finally do the update like so:

Meteor.users.update(updateUser._id, {$set: {profile: updateUser.profile}})

There has to be a better way? Any help would be greatly appreciated!

Thanks.

jpmoyn commented 8 years ago

I am by no means an expert, but from what you provided it seems like you are not using:

Collection.attachSchema(Schema)

If you attach the schema to the collection, your updates and inserts will validate against the schema automatically. This is really the beauty of collection2.

It seems like you have just been using simple schema in onCreateUser, which wouldn't be taking advantage of what collection2 has to offer. Though I could be misinterpreting your post.

I always define a collection, it's schema, and then attach the schema to the collection in one file. It's all right in the docs.

You definitely should not have to query the entire user object, and then replace the entire object every time you want to make a small update to the document.

Let me know if this helps.

aldeed commented 6 years ago

Closing old issues. Please comment if this is still an issue and should be reopened.