【问题标题】:How to save JSON array in to mongodb collection如何将 JSON 数组保存到 mongodb 集合中
【发布时间】:2015-06-13 08:31:28
【问题描述】:

我正在尝试将以下数组保存到 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信息是这样保存的

集合架构是

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

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

【问题讨论】:

    标签: json node.js mongodb mongoose bson


    【解决方案1】:

    您似乎将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
      }]      
    });
    

    【讨论】:

    • 哇非常感谢@Jason :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多