简体   繁体   English

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

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

Inside my libs folder I create collections using SimpleSchema. 在我的libs文件夹中,我使用SimpleSchema创建集合。 I want to add the Meteor.userId to some fields via autoValue like this: 我想通过autoValue将Meteor.userId添加到某些字段,如下所示:

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

When doing this however, I receive the following error: 但是,当这样做时,我收到以下错误:

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

I tried this as well: 我也尝试过这个:

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

This will crash my application though: 这会使我的应用程序崩溃:

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

Any ideas? 有任何想法吗?

userId information is provided to autoValue by collection2 through this userId信息collection2通过this提供给autoValue

The autoValue option is provided by the SimpleSchema package and is documented there. autoValue选项由SimpleSchema包提供,并在那里记录。 Collection2 adds the following properties to this for any autoValue function that is called as part of a C2 database operation: 对于作为C2数据库操作的一部分调用的任何autoValue函数,Collection2为此添加以下属性:

  • isInsert: True if it's an insert operation isInsert:如果是插入操作,则为True
  • isUpdate: True if it's an update operation isUpdate:如果是更新操作,则为True
  • isUpsert: True if it's an upsert operation (either upsert() or upsert: true) isUpsert:如果是upsert操作(upsert()或upsert:true),则为true
  • userId: The ID of the currently logged in user. userId:当前登录用户的ID。 (Always null for server-initiated actions.) (对于服务器启动的操作,始终为null。)

So your code should read as: 所以你的代码应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM