将子项添加到流星文档中

时间:2015-06-18 20:56:28

标签: mongodb meteor collections insert-update

我有一个具有以下数据结构的流星集“列表”。

   "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 个答案:

答案 0 :(得分: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}});