Node.js 发送邮递员数组中的对象数组始终为空
我试图使用Postman向mongodb发送一个对象数组,但子类别数组始终为空Node.js 发送邮递员数组中的对象数组始终为空,node.js,mongodb,postman,Node.js,Mongodb,Postman,我试图使用Postman向mongodb发送一个对象数组,但子类别数组始终为空 { "name": "Category 1", "subcategory": [ { "name": "value 1, value2" } ] } 我的猫鼬模式: const categorySchema = new mongoose.Schema({ name: { type: String, required:
{
"name": "Category 1",
"subcategory": [
{
"name": "value 1, value2"
}
]
}
我的猫鼬模式:
const categorySchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 255
},
subcategory: [
{
name: {
type: String
}
}
]
});
我的邮递员设置为“原始”,JSON(应用程序/JSON)
问题是您没有在收藏中保存
子类别
您可以尝试:
let category = new Category({
name: req.body.name,
subcategory : req.body. subcategory
});
我不知道我是否100%正确地回答了这个问题,但我猜您试图实现的是MongoDB中的以下结构:
"_id": "524b1894066496c34b",
"pickName": "Name",
"chosenAddress": [
{
"_id": "24b1894066496c34d",
"street": "Sample Street",
"number": "321"
},
{
"_id": "24b1894066496c34c",
"street": "Second One",
"number": "123"
}
如果是这样的话,有一个解决办法可以解决这个问题。在将其发送到后端(POST请求)之前,请确保您正在将对象转换为对象数组。
我怀疑您遇到了相同的问题,尝试发送对象而不是对象数组。
将其放入您的提交句柄中:
var result = Object.keys(this.state.formControls).map(key => ({ key, value: this.state.formControls[key] }));
上述参考:
相应地替换键和值
希望这会引导您,否则其他人可能会发现它很有用。我在模式中看到您在传递字符串数组时使用了名称:{type:String}
?您能说明如何将其保存到数据库中吗?我们已经看到了模式和请求体,请显示将请求体保存到数据库的代码collection@RaviShankarBharti啊对。这就是问题所在。只是现在我看不清楚该怎么修let category=new category({name:req.body.name})代码>谢谢,这几乎是对的,但是如何让数组中的每个项都有自己的ID呢?有了这个,我得到了一个有多个值的id。你说每个项目都有自己的想法是什么意思?默认情况下,mongoose会在每个级别的对象上插入\u id
,请尝试代码并检查数据库。我已经为您添加了一个屏幕截图。值1应该有自己的id,值2也应该有自己的id_id@user8463989如果您需要每个子文档都有自己的id,可以自己生成它,也可以将其设置为自己的集合