3

在我的 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.

有任何想法吗?

4

1 回答 1

3

userId信息autoValuecollection2通过提供this

autoValue 选项由 SimpleSchema 包提供,并记录在那里。Collection2 为作为 C2 数据库操作的一部分调用的任何 autoValue 函数添加以下属性:

  • isInsert:如果是插入操作则为真
  • isUpdate:如果是更新操作则为真
  • isUpsert:如果是 upsert 操作则为真(upsert() 或 upsert: true)
  • userId:当前登录用户的ID。(对于服务器启动的操作,始终为 null。)

因此,您的代码应为:

Collection = new Meteor.Collection('collection');
Collection.attachSchema(new SimpleSchema({
    createdByUser: {
        type: String,
        max: 20,
        autoValue: function() {
            return this.userId;
        }
    }
});
于 2015-10-31T16:20:49.400 回答