Boutran
Boutran

Reputation: 10124

Writing user entered text (input) back into it's document (in mongo)

I have a meteor template rendering a document comming out of mongo db. Parts of the document are editable (they render as html input elements). Now I need the data to flow back into the document (and into mongo),

What is the best way to do this ?

The answer is easy if I want to write back the value of doc.a :

doc = {a: "hello"}

it is less easy with : doc.a[0].z

doc = {a: [{z: "hello"}]}

because in order to do the update, the path must be remembered in order to write the update statement. Updating the whole document whenever a field changes looks simple, but inefficient...

It is an extremely common use case, some frameworks (EmberJs) have magical bindings that modifies the model whenever the widget's value changes.

How is this done in meteor ?

Upvotes: 3

Views: 467

Answers (1)

zorlak
zorlak

Reputation: 1404

As you point out, it would probably be inefficient to run a db update command whenever the input changes. This is especially true for draggable elements like sliders.

One thing you can do is separate the db query into a function, and then debounce it using underscore.js, like so (untested):

var debouncedUpdate = _.debounce(function(newObject) {
    CollectionName.update({_id: newObject._id},newObject);
},300,true);

Template.objectInput.events({
    'keydown #text-input': function(event) {
        var newValue = $(this.find('#text-input')).val();
        var self = this;
        self.value = newValue;
        debouncedUpdate(self);
    }, 
});

Upvotes: 2

Related Questions