add subitems to meteor document

39 views Asked by At

I have a meteor collection "list" that has the following data structure.

   "list" : [
  {
     "_id" : "id",
     "author" : "authorId",
     "createdOn" : "DateTime",
     "description" : "description",
     "items" : [
        {
           "item1" : {
              "itemComplete" : "Boolean",
              "itemName" : "item name",
              "itemDescription" : "item description",
           }
        },
        {
           "item2" : {
              "itemComplete" : "Boolean",
              "itemName" : "item name",
              "itemDescription" : "item description",
           }
        }
     ],

Users will be able to add arbitrary number of list items. I am trying to figure out how to add itemX programmatically. E.g. I have the following code (which does not work) that gives an idea of what I am trying to accomplish.

 var currentItemCount = Lists.find({_id:_currentListId, items:{}}).count() + 1;
 var newItemNum = "item" + currentItemCount;
 var newListItem = $("#list-item").val(); 
 Lists.update({_id:_currentListId},{$push : {items:{newItemNum:{itemName:newListItem}}}});

I would appreciate any suggestions or hints to help me fix my code. Please let me know if I am missing some information.

Thanks in advance.

Kamal

1

There are 1 answers

0
David Weldon On BEST ANSWER

Give something like this a try:

// fetch the current list
var list = Lists.findOne(_currentListId);

// find the number of existing items and handle the case where there are none
var numItems = (list.items || []).length;

// the the next item key will be one more than the length
var itemKey = 'item' + (numItems + 1);

// extract the item name from a form
var itemValue = {itemName: $('#list-item').val()};

// you can't use varaiable names as keys in object literals
// so we have to use bracket notation
item = {};
item[itemKey] = itemValue;

// push the new item onto the list of items
Lists.update(_currentListId, {$push: {items: item}});