Fred J.
Fred J.

Reputation: 6029

Meteor mapping documents to userId

This Meteor app has the accounts-password package.

Meteor.publish('tasks', function () {
  return Tasks.find({userId: this.userId});
});

How does Meteor know which document in the 'tasks' collection belong to which user? Do I need to add ownerId: Meteor.userId to every collection? Thanks

Upvotes: 0

Views: 30

Answers (2)

gaiazov
gaiazov

Reputation: 1960

A common way to do this is via before hook on the Tasks collection

Tasks = new Mongo.Collection('tasks');

Tasks.before.insert(function (userId, task) {
    task.userId = userId;
});

Tasks.before.upsert(function (userId, selector, modifier, options) {
    modifier.$set = modifier.$set || {};
    modifier.$set.userId = userId;
});

Upvotes: 1

David Weldon
David Weldon

Reputation: 64312

In a word, "yes". There's no magic going on here - the selector just says: "find all of the documents where the userId field equals the user id of the caller". It's up to you to make sure the userId (or ownerId or whatever you want to call it), is correctly written (usually on insert of the document).

Upvotes: 1

Related Questions