Meteor方法在服务器上创建插入挂钩并绑定userId

时间:2017-11-22 11:44:12

标签: meteor methods hook

我实现了一个钩子函数,我将一些createdAtupdatedAt字段附加到插入到集合中的doc。我可以将它附加到这样的任何集合:

export const insertHook = function (doc) {
    try {
        const user = Meteor.user();
        doc.createdBy = user && user._id ? user._id : null;
        doc.createdAt = new Date().getTime();
    } catch (e) {
        console.err(e);
    }
};

将钩子附加到集合基本上是通过构造函数中的第三个选项传递它:

class HookedCollection extends Mongo.Collection {

    constructor(name, options, hooks={}) {
        super(name, options);
        this.insertHook = hooks.insertHook;
    }

    insert(doc, callback) {
        if (this.insertHook && Meteor.isServer)
            this.insertHook.call(this, doc);
    }
}

export const MyDocs = new HookedCollection("mydocs", {}, {insertHook});

在Meteor方法中,我只是做一个正常的插入:

Meteor.methods({
    insertDoc:function(doc) {
        //check doc...
        return MyDocs.insert(doc);
    }
});

这基本上会产生以下错误:

Error: Meteor.userId can only be invoked in method calls or publications.

我尝试了bind的几种方法,但总是在这个错误中结束。是否真的没有办法将userId绑定到函数?

1 个答案:

答案 0 :(得分:1)

根据Meteor docs Meteor.userId()可以在任何地方使用,但发布功能(服务器端发布功能)。

您不是直接在方法中使用Meteor.userId(),而是在回调中使用userId(请参阅讨论in this github issue)。您可以将// Using Meteor.userId() Meteor.methods({ insertDoc:function(doc) { //check doc... return MyDocs.insert(doc, Meteor.userId()); } }); // Or using this.userId Meteor.methods({ insertDoc:function(doc) { //check doc... return MyDocs.insert(doc, this.userId()); } }); 信息作为方法中的参数传递给回调函数,例如:

Meteor.userId()

作为一般规则,在客户端(查询数据库)和服务器中的this.userId中使用STYLE | INVOICE_DATE2 A | 2017-01-03 B | 2017-01-03 C | 2017-01-03 A | 2017-02-03 A | 2017-01-03 B | 2017-02-03 B | 2017-01-03 。有关此问题的更多信息Meteor - Why should I use this.userId over Meteor.userId() whenever possible?Meteor forums

相关问题