首页 > 解决方案 > 使用moongose,nodejs在mongodb中插入带有嵌套数组的对象

问题描述

我正在尝试在 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 中,我检查了服务器正在接收一个带有空数组的对象......这正常吗?我正在学习,我是新的编程...

标签: node.jsmongodbmongoose

解决方案


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

[ "item": "whatever1" ]

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

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

推荐阅读