Useraccounts: Is it possible to use the username as the Mongo _id?

My application shall always have a username, and I would like to identify users by it. So I would like to set the username as the _id in MongoDB, without the need of copying it. Is it possible to set the _id on registration to the username and omit the additional username field?

I’m using useraccounts:core and already managed to add the username to the signup screen. But I did not find a way to tell AccountsTemplate to use the username as the _id.

What is the background of this question? It seems like a not smart idea and it will not work well. Meteor does not support it anyway.

If you need the username many times just denormalise it like normally.

Well, you can set additionals fields on registration, it’s not a problem, just use onUserCreate function. However, either username or email field has to be set in order for registration, that’s how accounts packages work in Meteor.

On the other hand, I agree with @lucfranken, I wouldn’t recommend the way you want to do it.

The reason is simple: I want to store references to the user at many other objects. If I store it as an id, I always have to use another find() on the user collection to get a display name for the respective user and hence have another roundtrip to the server. Since the users won’t be able to change their usernames, it would be easier to use them as the _id directly. Of course I could save the username directly at the objects instead of the _id, but that just did not “feel right”.

What you want to do feels much more “not right” in my opinion. :wink: I mean, when I see a field called _id, I expect it to be Mongodb’s objectID or Meteor’s own string id, not a username. Also when I see “waldgeist”, I expect it to be username, not id.

OK, maybe you’re right :smile:

Well, some people would see it in different light than me. Like in this SO answer.

Don’t do this. Instead simply denormalise it. In case you later need to be able to change usernames you can simply write a method which updates all collections, something like:

Collection1.update({userId: 123}, {$set: {username: 'newUserName'}})
Collection2.update({userId: 123}, {$set: {username: 'newUserName'}})

etcetera

So don’t do the roundtrip. Also because it’s very easy to add the username on create, it’s then always available.

1 Like