Handling changeable key value pairs in meteor collections (schemaless dilemma)


#1

How do you solve the problem when some of the key:values pairs in your .insert statement are optional (and thus your key:value pairs change all the time) while it’s being executed within a loop (I’m reading hundreds of rows from a table)?

As I only have only 6 mandatory fields in the collection and 6 optional fields I’m not sure how I can elegantly code it so that I don’t have to insert the empty values as well into my collection. With 6 optional fields I have (roughly if my math is correct) 36 different combinations that I have to handle in if clauses, not really practical. That’s a dilemma the schemaless MongoDB creates (unless I want to waste space and have many key:value pairs with empty values in my document).

I’ve tried using a string that is concatenated with the key:value pairs as a parameter. Which isn’t allowed in the .insert command (syntax error) as meteor expects a { key1:value1, key2:value2 } structure.

I could enter all key:value pairs at once and then fire up to 6 $unset to delete those fields again from the document but that isn’t really a practical solution (as it will create a lot of I/O operations when there really should only be 1 I/O operation).

Any suggestions? How do you solve the problem with changeable key value pairs in Meteor? Thanks in advance for your help!

This question is also posted at SO (please do answer there to create a reference)
Schemaless dilemma


#2

Your code should create the object as object litteral.
var obj1 = {foo:“1”, bar:“2”}
var obj2 = {foo:“3”} // no bar
Then you get Mongo to insert the objects
collection.insert(obj1);
collection.insert(obj2);


#3
insertedObject = {}
insertedObject[“price”] = itemPrice;
insertedObject[“name”] = itemName;
if (!! itemNote ) { 
  insertedObject["note"] = itemNote ; 
}
Products.insert(insertedObject);

same with selectors/projections in publications where you have optional arguments etc.