4

Update a nested collection in meteor is not a problem (and it is described here : Updating a nested property on a collection object with $set)

Basic way to do it :

Collection.update({sel}, {"$set" : {"address.city": "new address"}});

But what if I want to describe my path with variables ?

This one obviously does not work :

var cityName = "NYC";
Collection.update({sel}, {"$set" : {"address." + cityName: "new address"}});

Sadly this one does not work either:

var path = "address.NYC";
Collection.update({sel}, {"$set" : {path: "new address"}});

Neither does that one:

var object = {"address.NYC": "new address"};
Collection.update({sel}, {"$set" : object});

Well, actually, it works, but not the way I want it. It replace entirely the "address" object, removing the other properties.

Any ideas ?

Is there a way to select the field I want to update in the query part ?

Community
  • 1
  • 1
fabien
  • 2,228
  • 2
  • 19
  • 44

1 Answers1

4

It doesn't work because you can't use dynamic keys for object literals in javascript. You need to use bracket notation and build up the object you want to use in the update. For example:

var city = 'NYC';
var object = {};
object["address." + city] = 'new address';

MyCollectionName.update(idOfObjectToUpdate, {$set: object});

Your last example should work, assuming Collection is actually the name of a collection, and {sel} is the correct selector for what you are trying to do.

Community
  • 1
  • 1
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • worked perfectly ; thanks a lot :) But I am not sure to understand the difference between this and my last attempt. Could you explain ? – fabien Sep 02 '13 at 17:45
  • Great - I'm glad that helped. I don't see anything wrong with your last attempt. Building up the object and using a literal should be the same (minus the use of the variable). Perhaps you mistyped something. – David Weldon Sep 02 '13 at 18:00