у меня есть три поля в коллекции:
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. Это возможно?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы можете использовать метод this.field() внутри своей функции autoValue:
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
});
Спасибо, я попробую как можно скорее