【问题标题】:Using Mongoose, how do I insert key value pairs as objects into an array via a form?使用 Mongoose,如何通过表单将键值对作为对象插入到数组中?
【发布时间】:2012-09-23 17:05:19
【问题描述】:

考虑以下简单架构:

var PostSchema = new Post({
  body : String,
  tags : []
}

通过表单 POST(我正在开发的 REST HTTP API),我想将键/值对插入到 tags 数组中,以便生成的 mongodb 文档如下所示:

{
  "body" : "This is the post body",
  "tags" : [
              {"Color" : "Orange"},
              {"Color" : "Blue"},
              {"Person" : "Ted"},
              {"Person" : "Fred"},
              {"Person" : "Joe"},
              {"Stone" : "Diamond"}
           ]
}

我的问题是,如何命名tags 的表单字段来完成此操作?我正在为每种颜色考虑类似tags[0][color] 的东西,但这不起作用,它为标签数组中的每个键创建一个单独的数组,其中包含值列表。

【问题讨论】:

    标签: arrays forms node.js express mongoose


    【解决方案1】:

    我现在有点傻。解决方案是(显然)像这样提供tags

    tags[0][color] = orange
    tags[1][color] = blue
    tags[2][person] = ted
    tags[3][person] = fred
    tags[4][person] = joe
    tags[5][stone] = diamond
    

    我的大脑一直卡在将它们全部归入tags[0] - 不知道为什么。

    【讨论】:

      猜你喜欢
      • 2020-03-30
      • 2019-03-15
      • 2020-04-30
      • 2019-10-01
      • 2018-06-22
      • 2014-04-03
      • 2021-03-25
      • 2017-10-12
      • 2022-12-28
      相关资源
      最近更新 更多