rahul
rahul

Reputation: 3108

Mongoose Mixed type field not getting populated

I have a json doc that has embedded document which is variable (but in json format). So I use Mixed Schema type. When I save, everything works fine except the mixed type object doesn't get populated and won't save. What am I doing wrong here ? Updating --> What I mean is - everything works as expected except the data node (which is suppose to be of mixed type)

My Document Example:
{
    "data": {
        "user_name": "username",
    "cart_items": [
        {
            "sku": "ABCD",
            "msrp": 1250.25,
            "discount": 10,
            "final_price": 112.22
        },
        {
            "sku": "PQRSDF",
            "msrp": 12.25,
            "discount": 10,
            "final_price": 1.2
        }
    ]
},
"template_id": "1",
"from": "[email protected]",
"send_status": 0,
"priority": 99,
"app_id": "app3",
"_id": "532a54aa1c76fba0874c48ea",
"bcc": [],
"cc": [],
"to": [
  {
    "name": "acv",
    "email": "[email protected]"
  },
  {
    "name": "pem",
    "email": "[email protected]"
  }
    ],
    "call_details": {
      "data_id": "01234",
      "event_id": 25
    }
  }
code to insert:
Schema definition:
 app_id : { type: String, trim: true },
    priority:  { type: Number},
    send_status:  { type: Number},
    call_details : {
        event_id : { type: Number},
        data_id : { type: String, trim: true },
        id : false
                },
    from :  { type: String,  trim: true },
    to : [addressSchema],
    cc : [addressSchema],
    bcc : [addressSchema],
    template_id : { type: String, trim: true },
    data:  {  any: {}  }

Code:
r.app_id = req.body.app_id;
        r.priority= req.body.priority;
        r.send_status= req.body.send_status;
        r.call_details.event_id= req.body.call_details.event_id;
        r.call_details.data_id= req.body.call_details.data_id;
        r.from= req.body.from;
        r.to = populate_address(req.body.to);
        r.cc = populate_address(req.body.cc);
        r.bcc = populate_address(req.body.bcc);
        r.template_id= req.body.template_id;
        r.data =req.body.data);
        r.markModified('data');


        r.save(function (err){
            console.log("add");
            res.send ("added");
        });

Upvotes: 0

Views: 1270

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311935

As you currently define your schema, it will only save the any field within data.

Remove the any embedded field from the definition for data in your schema.

So instead of:

data:  {  any: {}  }

Use:

data:  {}

Upvotes: 1

Jayram
Jayram

Reputation: 19578

As mongoose does not handle the embedded document save automatically. You need to save the embedded document first and assign the object ID to the parent schema as reference.

Upvotes: 0

Related Questions