【问题标题】:add subitems to meteor document向流星文档添加子项
【发布时间】:2015-09-04 16:48:19
【问题描述】:

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

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

如果有任何建议或提示可以帮助我修复我的代码,我将不胜感激。如果我遗漏了一些信息,请告诉我。

提前致谢。

卡马尔

【问题讨论】:

    标签: mongodb meteor collections insert-update


    【解决方案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}});
    

    【讨论】:

      猜你喜欢
      • 2015-12-21
      • 2016-12-13
      • 1970-01-01
      • 2017-02-22
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多