[英]Meteor Collections Simpleschema, autovalue depending on other field values
我在集合中有三個字段:
Cards.attachSchema(new SimpleSchema({
foo: {
type: String,
},
bar: {
type: String,
},
foobar: {
type: String,
optional: true,
autoValue() {
if (this.isInsert && !this.isSet) {
return `${foo}-${bar}`;
}
},
},
);
所以我想讓foobar字段作為auto(或默認)值(如果未顯式設置)以返回foo和bar的兩個值。 這可能嗎?
您可以在autoValue
函數中使用this.field()
方法:
Cards.attachSchema(new SimpleSchema({
foo: {
type: String,
},
bar: {
type: String,
},
foobar: {
type: String,
optional: true,
autoValue() {
if (this.isInsert && !this.isSet) {
const foo = this.field('foo') // returns an obj
const bar = this.field('bar') // returns an obj
if (foo && foo.value && bar && bar.value) {
return `${foo.value}-${bar.value}`;
} else {
this.unset()
}
}
},
},
);
相關閱讀: https : //github.com/aldeed/simple-schema-js#autovalue
但是,您也可以通過在集合的insert
方法上使用鈎子來解決此問題。 在那里,您可以假定存在值foo
和bar
,因為您的架構要求它們:
Cards.attachSchema(new SimpleSchema({
foo: {
type: String,
},
bar: {
type: String,
},
foobar: {
type: String,
optional: true,
},
);
Cards.after.insert(function (userId, doc) {
// update the foobar field depending on the doc's
// foobar values
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.