How I can separate data by logged user

Hello. Maybe it is a stupid question but if I want to retrieve data only for current logged in user shoul I populate user id to each collection. Or Meteor provide another way to do it.
Thanks.

Hi there, yup adding the user id to the collection is the way to go, something along the lines of:

Meteor.methods({
  insertDog: function(myDog) {  
      var user = Meteor.user();

      if (user) {  
          check(myDog, {
                name: String,
                breed: String
            });

            var dog = _.extend(myDog, {      
                ownerId: user._id
            });

            Dogs.insert(dog);
        }
    }

@riebeekn thank you for your reply

There are a few ways to do it. In your templates you can use {{currentUser}} which is the current logged in user document complete with everything that you publish about the user. An example of that would be

<h1>Hi, {{currentUser.profile.firstname}}!</h1>

Another way would be to only pub/sub to the documents of the currently signed in user which would look something like this.

// Server side
Meteor.publish("userPosts", function(userId){
    return Posts.find({createdBy: userId})
})

//client side
Meteor.subscribe("userPosts", Meteor.userId())

Then wherever you are subscribed to userPosts you can run queries that will only return documents for the currently logged in user.

I always have these three fields in each of my collections

  • userId - String
  • createdAt - Date
  • lastUpdate - Date

This is really useful information. And if you are using simple-schema then you can create a base schema and have all of your collections combine with the base schema. so you dont have to repeat your self.

1 Like

Good point about using simple-schema and / or collection2 to add the user id to a collection.

Great solution use simple-schema to add standard field to every collection without repeating! Thanks. It is exactly what I want.