Replace document attributes in publish function

I am using a meteorite and I have a question about the publish function (server side)

Meteor.publish('users', function () { .... }

I send documents to a browser that have the identifier of other collections. For example, a Task document belongs to a project.

{ 
    title: '....',
    projectId: 'KjbJHvJCHTCJGVY234',
    ...
}

I want to add a property to this document projectTitle, so I do not need to search for a project on the client. However, when I add this property to a function publish, it is not sent to the client. This is what I tried:

Meteor.publish('tasks', function () {
    var tasks = Tasks.find();

    tasks.forEach(function (task) {
       var project = Projects.findOne({_id: task.projectId});
       task.projectTitle = project.title;
    });

    return tasks;
}

Any suggestions for changing documents (not persistent) inside the publish function?

+1
source share
2 answers

You can do it:

Meteor.publish("tasks", function() {

    var transform = function(task) {
        var project = Projects.findOne({_id: task.projectId});
        task.projectTitle = project.title;
        return task;
    }

    var self = this;

    var tasks = Tasks.find().observe({
        added: function (document) {
            self.added('tasks', document._id, transform(document));
        },
        changed: function (newDocument, oldDocument) {
            self.changed('tasks', document._id, transform(newDocument));
        },
        removed: function (oldDocument) {
            self.removed('tasks', oldDocument._id);
        }
    });

    self.ready();

    self.onStop(function () {
        tasks.stop();
    });

});

, "" .

+2

, .fetch() . var tasks = Tasks.find().fetch();

0

Source: https://habr.com/ru/post/1569773/


All Articles