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

时间:2015-04-08 11:45:59

标签: json node.js mongodb mongoose 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"}]}

以下是 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);
    }

虽然执行了查询,但功能信息以这种方式保存 enter image description here

收集架构

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

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

1 个答案:

答案 0 :(得分:4)

您似乎将features声明为架构中的String而不是子文档数组。因此,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
  }]      
});