Meteor Autoform中defaultValue和autoValue之间的差异?
我正在做一个项目,我从使用autoValue开始Meteor Autoform中defaultValue和autoValue之间的差异?,meteor,meteor-autoform,simple-schema,Meteor,Meteor Autoform,Simple Schema,我正在做一个项目,我从使用autoValue开始 程序。附件模式(新简单模式)({ 创建人:{ 类型:字符串, autoValue:function(){ 返回这个.userId }, 可选:true, 自动形成:{ 类型:“隐藏” } }, 创建数据:{ 类型:日期, 标签:“创建于”, defaultValue:新日期(), 可选:true, 自动形成:{ 类型:“隐藏” } } })); 在我需要其他用户更新信息之前,一切都可以找到,比如admin、Programs.update或Pr
程序。附件模式(新简单模式)({
创建人:{
类型:字符串,
autoValue:function(){
返回这个.userId
},
可选:true,
自动形成:{
类型:“隐藏”
}
},
创建数据:{
类型:日期,
标签:“创建于”,
defaultValue:新日期(),
可选:true,
自动形成:{
类型:“隐藏”
}
}
}));
在我需要其他用户更新信息之前,一切都可以找到,比如admin、Programs.update或Programs.insert方法将更改电子邮件字段
我试图为createdBy字段使用defaultValue,但
defaultValue:this.userId
返回空值
而且我不允许使用
defaultValue:Meteor.userId()
有人能解释这两者的区别吗?我尝试使用function(){return this.userId}作为defaultValue,但仍然没有成功您应该试试这个代码段
new SimpleSchema({
// ...
createdBy: {
autoValue() {
return Meteor.userdId();
}
}
// ...
})
现在的解释是,您的问题更可能与这个
绑定,this.userId,是从SimpleSchema上下文中以这种方式调用的,它没有任何userId()
方法,在这种情况下,您应该使用完整的命名空间Meteor.userId()
关于这个
绑定的非常酷的解释,我建议您阅读
defaultValue
由简单模式用于定义默认值。有一些怪癖,所以请阅读文档:
想想什么时候运行代码,你就会明白为什么不能对defaultValue
使用Meteor.userId()
或this.userId
。模式在启动时运行一次
允许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;
},
}
}));
只是一个后续问题,我发现,如果我也将autovalue字段设置为hidden,我就不能在客户端进行修改。我想这和更新过程中未定义的输入值有关,但我还没有涉及到它,我不确定你们在问什么。客户端本质上是不可信的,但如果要强制自动计算值,请注意
clean
方法