node.js - 使用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 中,我检查了服务器正在接收一个带有空数组的对象......这正常吗?我正在学习,我是新的编程...
解决方案
您的有效载荷似乎不正确。
[ "item": "whatever1" ]
不是有效的 JSON,不会被正确解析。尝试将您的有效负载更改为:
{
"client": "Jhon"
"items": [
{ "item": "whatever1" },
{ "item": "whatever2" }
]
}
推荐阅读
- r - 强制尺寸美学缩放到给定的休息时间
- sql-server - where 子句中的动态 T-SQL 存储过程
- ios - 如何在 Swift 中进行逆正则表达式匹配 [regex negation]?
- javascript - 为什么这里需要setter?
- react-native - 有哪些规则可以让你的代码看起来高效?
- javascript - .save 不是函数,并且 .findOneAndUpdate() 不会更新我的数据库
- php - 计算实体中的字段,按学说排序
- jenkins - Jenkins:如何选择同一标签下的代理
- hyperledger-fabric - 一个节点可以在两个不同的结构网络中吗?
- c++ - 我应该如何使用条件变量解决哲学家就餐问题?