在发布功能中替换文档的属性 [英] Replace attributes of a document in publish function

查看:50
本文介绍了在发布功能中替换文档的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用meteor,我对发布功能(服务器端)有疑问

I'm using meteor and I have a question about the publish function (server side)

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

我现在正在向浏览器发送文档具有其他集合的id。例如,任务文档属于项目

I'm sending now documents to the browser which have id's of other collections. For example the Task document belongs to a project

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

我想要的是在此文档中添加一个属性 projectTitle 所以我不必在客户端上查找项目。但是,当我在发布函数中添加此属性,它不会发送到客户端。这是我尝试过的:

What I want is to add a property to the this document projectTitle so I don't have to look up the project on the client. However, when I add this property in the publish function it is not send to the client. This is what I've 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;
}

如何修改发布函数中的文档(非持久性)? / p>

Any suggestions how to modify documents (not persistent) inside the publish function?

推荐答案

你可以这样做:

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();
    });

});

那里有很多自定义逻辑,但'transform'基本上添加了属性。

There's a lot of custom logic there, but the 'transform' basically adds the attributes in.

这篇关于在发布功能中替换文档的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆