Assume there is a little form like this
<form>
<input type="text" name="title">
<input type="text" name="unit">
<input type="checkbox" name="specific">
</form>
On a change
-event I want to save the new data to the DB via validated methods:
'change form input': function (event) {
const $this = $(event.target);
let updates = { id: FlowRouter.getParam('docId') };
if ($this.attr('name') == "specific") { updates.specific = !!$this.is(':checked'); }
else if ($this.attr('name') == "title") { updates.title = $this.val(); }
else if ($this.attr('name') == "unit") { updates.unit = $this.val(); }
updateMetadata.call(updates);
}
As you can see, there is one event and depending on which input field has changed, the object would be different. And exactly this is my problem. Because I would define my schema like this:
var Schema = {};
Schema.metadata = new SimpleSchema({
id: { type: String, regEx: SimpleSchema.RegEx.Id },
specific: { type: Boolean },
title: { type: String },
unit: { type: String }
});
For using in the method:
export const updateMetadata = new ValidatedMethod({
name: 'update.metadata',
validate: Schema.metadata.validator(),
run({ id, specific, title, unit }) {
Collection.update(
{ _id: id },
{
$set: {
specific: specific,
title: title,
unit: unit
}
}
);
}
});
But this is quite bad, as the $set
should just use the needed fields (which is set in updates
) - right now the other fields are set to undefined
. Also there have to be all variables in the run()
and not only these, which are used.
I thought about using pick
, but I can’t use pick depending on the content, which I want to validate. So if there is update.titles
I would pick just title
from the schema…
So what would be the recommended way: Should I define a own method for each input-field by using separated events on each field? Sounds also quite bad to me…