What is the alternative to mongodb array positional modification in meteor.js?


#1

For the life of me, I can’t figure out how to update a collection, because minimongo does not support positional array modification. Been trying for hours but keep going in circles. If anybody can help me, I will be forever grateful :slight_smile:

Here is the structure of my collection.

The main collection is users, each user has a set of rules. The rules structure is the following.

 rules [ 
{key:{value : "someValue" , date_created:"someDate1" ,date_updated :"someDate" } } ,  
{key1: {value : "someValue2" , date_created:"someDate2",date_updated :"someDate" } } }
]

I need to update value, and date_updated. I have the key value (in variable form.) How can I perform this update?

My new rules structure would look like the following afterwards:

 rules [ 
 {key:{value : "**someNEWValue**" , date_created:"someDate1" ,date_updated :"**someNEWDate**" } } ,  
 {key1: {value : "someValue2" , date_created:"someDate2",date_updated :"someDate" } } }
 ]

Considering meteor doesn’t support positional array modification, I am struggling with this dearly. Any workarounds ???
Thank you.
Alex


#2

Don’t know why your rules is an array of objects containing a single key referencing an object instead of just being a hash, but maybe something like this works?

var newRules = [];
var keyToUpdate = 'key1';
rules.forEach(function(rule){
 if(keyToUpdate in rule)
 {
  rule[keyToUpdate].value=someNEWValue;
  rule[keyToUpdate].date_updated=someNEWDate;
 }
 newRules.push(rule);
});
Collection.update(...,{$set:{rules: newRules}});

In general it would be easier if

rules: {
 key: {},
 key2: {},
}

Then you could simply

rules[keyToUpdate].value = someNEWValue;
rules[keyToUpdate].date_updated = someNEWDate;

or even

var set = {};
set['rules.'+keyToUpdate+'.value']=someNewValue;
set['rules.'+keyToUpdate+'.date_updated']= someNEWDate;
Collection.update(..., {$set: set});