Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/439.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 基于动态模板向集合添加元素_Javascript_Mongodb_Meteor - Fatal编程技术网

Javascript 基于动态模板向集合添加元素

Javascript 基于动态模板向集合添加元素,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,因此,我有一个投票模板,可以有用户想要的问题。如何将所有问题插入集合的元素中?因为我以前只有三个,所以我手动插入它们,如下所示: var newPoll = { question: event.target.question.value, choices: [ { text: event.target.choice1.value, votes: 0 }, { text: event.target.choi

因此,我有一个投票模板,可以有用户想要的问题。如何将所有问题插入集合的元素中?因为我以前只有三个,所以我手动插入它们,如下所示:

var newPoll = {
          question: event.target.question.value,
          choices: [
            {  text: event.target.choice1.value, votes: 0 },
            {  text: event.target.choice2.value, votes: 0 },
            {  text: event.target.choice3.value, votes: 0 }
          ],
          usersWhoVoted: [],
          poll_is_open: true,
          time_poll_closed: null,
 };

如果我现在可以有任意多个选项,如何插入所有选项?

如果您已经实现了本地集合来存储
选项
相关数据,您可以使用函数来循环您的集合,将适当的对象返回到数组中,并最终设置相应的数据:

if (Meteor.isClient) {
    Template.pollForm.events({
        'click #save-form': function(event, template) {
            var choices = Choices.find().map((choice) => ({
                text: template.find("input[name=" + choice.name + "]").value,
                votes: 0
            }));
            var newPoll = {
                question: event.target.question.value,
                choices: choices,
                usersWhoVoted: [],
                poll_is_open: true,
                time_poll_closed: null
            };
            Polls.insert(newPoll);
        }
    });
}

你使用本地集合吗?它只是一个数组,所以首先识别它(
newPoll.question
),然后向它添加内容(
newPoll.question.push({})
)。@MatthiasEckhart是的