2015-06-18 108 views
1

我有一個具有以下數據結構的流星集「列表」。將子項添加到流星文件

"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", 
      } 
     } 
    ], 

用戶將能夠添加任意數量的列表項目。我想弄清楚如何以編程方式添加itemX。例如。我有下面的代碼(不起作用),它提供了我想要完成的工作。

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}}}}); 

我將不勝感激任何建議或提示,以幫助我修復我的代碼。如果我缺少一些信息,請告訴我。

在此先感謝。

卡邁勒

回答

1

給這樣的一個嘗試:

// 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}}); 
+0

感謝一大堆!這很好用! – Kamal