gpt4 book ai didi

json - 如何将 JSON 数组保存到 mongodb 集合中

转载 作者:可可西里 更新时间:2023-11-01 10:00:44 25 4
gpt4 key购买 nike

我正在尝试将以下数组保存到我在 mongodb 中的文档中

    {"Category_Id":"54c9c206e1f512456ada778b","Sub_category_Id":"54c9c24ee1f512456ada778d",
"features":[{"specification_field_type":"textbox","specification_name":"color","_id":"551e5f2e3bbe4691142bdeba","__v":0,"$$hashKey":"object:95"},
{"specification_field_type":"textbox","specification_name":"Call Features","_id":"551e616d3bbe4691142bdebf","__v":0,"$$hashKey":"object:97"}]}

这是我的 node.js 代码,用于将帖子值保存在 mongodb

var Category_Id = req.body.Category_Id;
var Sub_category_Id = req.body.Sub_category_Id;
var features = req.body.features;
var property =new db.properties();
property.Category_Id = Category_Id;
property.Sub_category_Id = Sub_category_Id;
property.features = features;

property.save(function (err){
var message = JSON.parse('{"status":"success","message":"Features added"}');
return res.send(200, message);
}

虽然执行了查询,但是features信息是这样保存的 enter image description here

集合架构是

var properties = new Schema({
Category_Id : { type: String},
Sub_category_Id : { type: String},
features : { type: String}
});

谁能帮我解决这个问题。谢谢。

最佳答案

您似乎将 features 声明为架构中的字符串,而不是子文档数组。因此,Mongoose 在保存之前将数组从 req.body 转换为字符串。对您的模式进行以下调整应该会让您走上正确的轨道:

var properties = new Schema({
Category_Id : { type: String},
Sub_category_Id : { type: String},
features : [{
specification_field_type": String,
specification_name: String
// any other paths for features
}]
});

关于json - 如何将 JSON 数组保存到 mongodb 集合中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29513702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com