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

Ram*_*u.d 2 json mongoose mongodb node.js bson

我正在尝试将以下数组保存到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"}]}
Run Code Online (Sandbox Code Playgroud)

这是我的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);
    }
Run Code Online (Sandbox Code Playgroud)

虽然执行了查询,但是特征信息是这样保存的 在此处输入图片说明

集合架构是

var properties = new Schema({
    Category_Id : { type: String},
    Sub_category_Id : { type: String},
    features : { type: String}      
});
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题。谢谢。

Jas*_*ust 5

您似乎features在架构中声明为字符串,而不是子文档数组。因此,猫鼬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
  }]      
});
Run Code Online (Sandbox Code Playgroud)