Ramaraju.d
Ramaraju.d

Reputation: 1353

How to save JSON array in to mongodb collection

I am trying to save the following array into my document in 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"}]}

Here is my node.js code to save the post values in 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);
    }

Though the query is executed, the features information is saved in this way enter image description here

Collection schema is

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

Can someone help me to fix this. Thanks.

Upvotes: 2

Views: 9171

Answers (1)

Jason Cust
Jason Cust

Reputation: 10899

It appears you declared features to be a String in your schema instead of an Array of subdocuments. Mongoose is therefore casting the array from req.body to a string before it is saved. The following tweak to your schema should get you on the right track:

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
  }]      
});

Upvotes: 5

Related Questions