bp123
bp123

Reputation: 3417

How to correctly use this.added

I'm trying to publish a collection and I would like to add in a field that doesn't exist in the collection. I might be way off track here but I thought I could use this.added() to add fields to the published collection. Can someone please show me what I'm doing wrong

Meteor.publish('job.view-open-to-candidate', function(jobCollectionId) {
  const job = Jobs.find({ _id: jobCollectionId }, {
    fields: {
      candidateApplication: 0
    }
  });

  this.added('job', jobCollectionId, {testNewField: 'test'})

  return job;
});

Upvotes: 0

Views: 186

Answers (1)

Styx
Styx

Reputation: 10076

If you want to modify documents in publication you should use Cursor.observe() or Cursor.observeChanges().

The most common pattern for that is (with modification you need):

Meteor.publish('job.view-open-to-candidate', function(jobCollectionId) {
  const publication = this;

  const handle = Jobs.find({ _id: jobCollectionId }, {
    fields: {
      candidateApplication: 0
    }
  }).observeChanges({
    added(_id, fields) {
      const newFields = fields;
      newFields.testNewField = 'test';
      publication.added('jobs', _id, newFields);
    },

    changed(_id, fields) {
      const newFields = fields;
      newFields.testNewField = 'test';
      publication.changed('jobs', _id, newFields);
    },

    removed(_id) {
      publication.removed('jobs', _id);
    },
  });

  this.ready();

  this.onStop(() => {
    handle.stop();
  });
});

Upvotes: 2

Related Questions