【问题标题】:inserting an objet with nested arrays in mongodb with moongose, nodejs使用猫鼬,节点js在mongodb中插入具有嵌套数组的对象
【发布时间】:2019-02-04 14:53:37
【问题描述】:

我正在尝试在 mongodb 中插入这样的对象。

   {
    "client" : "Jhon"
    "items" : [
                [
                 "item": "whatever1",             
                ],
                [
                 "item": "whatever2",
                ]
     ]
   }

我正在使用 Mongoose,所以我有这样的架构。

const itemSchema= new Schema({
    item: { type: String, required: true },
})

const clientSchema = new Schema({
    client: { type: String, required: true },
    items: [itemSchema],
})

在我将对象发送到我的 nodejs 服务器并创建文档后,我检查创建的文档,“items”是一个仅包含 _id: 的数组,仅此而已。

我这样创建文档。

createClient = (req, res) => {
    console.log(req.body); // Here i check what is receiving the server.
    clientModel.create(req.body).then(() => res.json('saved'));
}

在 req.body 中,我检查了服务器正在接收一个带有空数组的对象...这正常吗?我正在学习,我是新的编程人员......

【问题讨论】:

  • 客户端如何发送请求?似乎您没有从客户端获取任何数据,因为您有一个空的req.body
  • 我只是在使用 Postman,有趣的是对象已经创建,我可以看到 { "client": "Jhon", "Items": [ [{"_id":48327489237} ],[{"_id":753894758937}] } 所以它正在创建 nestead 数组但没有插入......正如我所说......很少见......我检查了 console.log(req.body) 并没有在数组内部...

标签: node.js mongodb mongoose


【解决方案1】:

您的有效负载似乎不正确。

[ "item": "whatever1" ]

不是有效的 JSON,不会被正确解析。尝试将您的有效负载更改为:

{
  "client": "Jhon"
  "items": [
    { "item": "whatever1" },
    { "item": "whatever2" }
  ]
}

【讨论】:

  • 完美!正在运行,似乎没有正确解析,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 2015-09-21
  • 2021-04-02
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 2022-07-20
相关资源
最近更新 更多