9

Trying to loop on all updated field I've got and update them dynamically before saving.

Product.findOne({ _id: productNewData['_id'] }, function (err, doc) {
  for (var key in productNewData) {
    # what do I do here?
  }
  doc.save();
});

I know that ruby has a send method like this:

doc.send(key) = productNewData[key]

I guess I can validate the params given and use eval. Is there any other way?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
WebQube
  • 8,510
  • 12
  • 51
  • 93

1 Answers1

16

They are two way to acces properties in Javascript: Using dot notation or brackets. Example:

var foo = {bar: 42}
foo.bar // 42
foo["bar"] // 42
var v = "bar"
foo[v] // 42
foo.v // undefined

So:

Product.findOne({ _id: productNewData['_id'] }, function (err, doc) {
  for (var key in productNewData) {
     doc[key] = productNewData[key]
  }
  doc.save();
});
Vinz243
  • 9,654
  • 10
  • 42
  • 86