Dynamically create Meteor.js MongoDB query

For some reason I am having a hard time getting this to work. I have a Mongo collection called "cats" and another called "rows". The field cat

in 'cats' is currentCat

. Then I want to be able to update the document in "rows" by referencing an existing document from _id

. No problem. But for each, currentCat

I want to add an element to the document "rows" with currentCat

as a field and something else as a value ( currentPer

). I came up with this:

var cats = Cats.find({owner: Meteor.userId()}, {fields: {cat: 1, per: 1}});

cats.forEach(function(cats) { //Inserts the rest of the row
  var currentCat = cats['cat'];
  var currentPer = cats['per'];
  var currentAmount = Math.round(amount*currentPer*100)/100;

  Rows.update(
    { _id: row },
    { $push: { currentCat: currentAmount } }
  );
});

      

( row

is the ID of the document I want to change)

Of course it doesn't work as expected and just inserts ...{currentCat: 57}

instead of the variable's value currentCat

. Then I tried to create a request object (as described here ):

var query = ({ _id: row }, { $push: { currentCat: currentAmount } })

It also failed, but this time with a remarkably descriptive error message:

Error: Invalid modifier. Modifier must be an object.

Any help would be greatly appreciated, as I have spent hours and countless google searches (although the answer is probably obvious and I just can't see it - I'm still trying to get used to Meteor after PHP).

EDIT . I want the finished document to look something like this:

 { "_id" : "PshEYKebccw7eYaTo", 
   "createdAt" : ISODate("2014-11-26T00:52:51.840Z"),
   "cat1" : 312,
   "cat2" : 564,
   "owner" : "GiWCb8jXbPfzyc5ZF",
   "text" : "asdf" 
}

      

+3


source to share


1 answer


$push

intended only for working with arrays. Based on your example Row doc, you don't really need an array operation here.

Try to simply set the margins in the Row document for each new cat value.



  var catData = {};
  catData[currentCat] = currentAmount;
  // As an example, catData now looks like {'cat1': 312}

  Rows.update(
    { _id: row },
    { $set: catData }
  );

      

+2


source







All Articles