向流星文档添加子项
add subitems to meteor document
我有一个具有以下数据结构的流星集合 "list"。
"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}}}});
如果有任何建议或提示可以帮助我修复代码,我将不胜感激。如果我遗漏了一些信息,请告诉我。
提前致谢。
卡迈勒
试试这样的东西:
// 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}});
我有一个具有以下数据结构的流星集合 "list"。
"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}}}});
如果有任何建议或提示可以帮助我修复代码,我将不胜感激。如果我遗漏了一些信息,请告诉我。
提前致谢。
卡迈勒
试试这样的东西:
// 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}});