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

Meteor method create insert hook and bind userId on the server

我实现了一个挂钩函数,我将一些 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绑定到函数上吗?

根据 Meteor docs Meteor.userId() 除了发布功能(服务器端发布功能)之外的任何地方都可用。

您没有在方法中直接使用 Meteor.userId(),而是在回调中使用(参见讨论 in this github issue)。您可以将 userId 信息作为方法的参数传递给回调函数,例如:

// 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。其他问题中的更多信息 and in Meteor forums