Autoform中defaultValue和autoValue之间的区别?

时间:2017-05-10 08:24:13

标签: meteor meteor-autoform simple-schema

我正在开发一个项目,我首先使用autoValue作为

Programs.attachSchema(new SimpleSchema({ createdBy: { type: String, autoValue: function() { return this.userId }, optional: true, autoform: { type: 'hidden' } }, createdAt: { type: Date, label: "Created At", defaultValue: new Date(), optional: true, autoform: { type: 'hidden' } } }));

一切正常,直到我需要更新其他用户的信息,比方说admin,Programs.update或Programs.insert方法将更改电子邮件字段。

我尝试将defaultValue用于createdBy字段,但

defaultValue: this.userId

返回null

我不允许使用

defaultValue: Meteor.userId()

任何人都可以解释这个区别吗?我尝试使用function(){return this.userId} for defaultValue仍然没有运气

2 个答案:

答案 0 :(得分:0)

你应该尝试这个片段,

new SimpleSchema({
   // ...
   createdBy: {
      autoValue() {
         return Meteor.userdId();
      }
   }
   // ...
})

现在解释一下,你的问题更可能与this绑定有关,this.userId是从SimpleSchema上下文调用的,这样就没有任何userId()方法,你应该使用这种情况下的完整命名空间Meteor.userId();

关于this绑定的一个非常酷的解释我建议你阅读 This binding

答案 1 :(得分:0)

simple-schema使用

defaultValue来定义默认值。有一些怪癖,请阅读文档:https://github.com/aldeed/meteor-simple-schema#defaultvalue

考虑代码运行的时间,您就会明白为什么不能将Meteor.userId()this.userId用于defaultValue。架构在启动时运行一次。

允许autoValue工作的是它返回一个函数。该功能在数据库更新/插入期间运行。阅读文档以完全理解它:https://github.com/aldeed/meteor-simple-schema#autovalue

现在,如果我理解您的问题,当管理员出现并修改文档时,您会遇到autoValue的问题?导致createdBy设置为管理员的ID?要解决类似问题,您只需要更具体地使用autoValue函数。

查看此代码是否有助于指导您正确的方向:

Programs.attachSchema(new SimpleSchema({
  createdBy: {
    type: String,
    autoValue: function() {
      if (this.isInsert) {
        return this.userId;
      } else if (this.isUpsert) {
        return { $setOnInsert: this.userId };
      }

      this.unset(); // Prevent user from supplying their own value
      return undefined;
    },
    optional: true,
     autoform: {
       type: 'hidden'
     }
  },
  createdAt: {
    type: Date,
    label: 'Created At',
    defaultValue: new Date(),
    optional: true,
    autoform: {
      type: 'hidden'
    },
    autoValue: function() {
      if (this.isInsert) {
        return new Date();
      } else if (this.isUpsert) {
        return { $setOnInsert: new Date() };
      }

      this.unset(); // Prevent user from supplying their own value
      return undefined;
    },
  }
}));
相关问题