如何通过 autoValue 将 Meteor.userId() 添加到 SimpleSchema?

How to add Meteor.userId() to SimpleSchema via autoValue?

在我的 libs 文件夹中,我使用 SimpleSchema 创建集合。我想通过 autoValue 将 Meteor.userId 添加到某些字段,如下所示:

Collection = new Meteor.Collection('collection');
Collection.attachSchema(new SimpleSchema({
    createdByUser: {
        type: String,
        max: 20,
        autoValue: function() {
            return Meteor.userId();
        }
    }
});

然而,当这样做时,我收到以下错误:

Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.

我也试过这个:

var userIdentification = Meteor.userId();
Collection = new Meteor.Collection('collection');
Collection.attachSchema(new SimpleSchema({
    createdByUser: {
        type: String,
        max: 20,
        autoValue: function() {
            return userIdentification;
        }
    }
});

虽然这会使我的应用程序崩溃:

=> Exited with code: 8
=> Your application is crashing. Waiting for file change.

有什么想法吗?

userId 信息通过 this

提供给 autoValue by collection2

The autoValue option is provided by the SimpleSchema package and is documented there. Collection2 adds the following properties to this for any autoValue function that is called as part of a C2 database operation:

  • isInsert: True if it's an insert operation
  • isUpdate: True if it's an update operation
  • isUpsert: True if it's an upsert operation (either upsert() or upsert: true)
  • userId: The ID of the currently logged in user. (Always null for server-initiated actions.)

因此您的代码应为:

Collection = new Meteor.Collection('collection');
Collection.attachSchema(new SimpleSchema({
    createdByUser: {
        type: String,
        max: 20,
        autoValue: function() {
            return this.userId;
        }
    }
});