Trialcoder
Trialcoder

Reputation: 6014

How to save child Schema in mongodb using mongoose

Following is my order object that I am trying to save -

{ 
  shipper: 
     { firstName: 'Test ShipName',
       address1: '10 Florida Ave',
       phone1: '800-123-4567' },
    consignee: 
     { firstName: 'AAA Manufacturing',
       address1: '100 Main Street' },
    items: 
    [ 
      { length1: 45, weight1: 12, height1: 45, width1: 34 },
      { length2: 42, weight2: 34, height2: 90, width2: 54 }
    ]
}

On doing this -

        Order(order).save(function(err, result){
            if(err)
                throw err;
            console.log(result);
        });

shipper, consignee are saving appropriate values but in database(mongodb), items are not saving properly -

"items" : [
    {
        "_id" : ObjectId("54e36e18c59700b513a5309d")
    },
    {
        "_id" : ObjectId("54e36e18c59700b513a5309c")
    }
],

Following is my oderSchema -

var orderSchema = mongoose.Schema ({
    shipper: {type: addressSchema, 'Default':''}},      
    consignee: {type: addressSchema, 'Default':''} },
    items: {type: [itemSchema], 'Default':''} },
});

Following is my itemSchema -

var itemSchema = mongoose.Schema({
  length: {type: Number, required: false },
  width: {type: Number, required: false },
  height: {type: Number, required: false }, 
  weight: {type: Number, required: false }, 
}); 

Let me know what I am doing wrong in saving the item info.

Upvotes: 0

Views: 658

Answers (1)

Yuri Zarubin
Yuri Zarubin

Reputation: 11677

In your itemSchema, the properties are "length", "width" etc, however properties of the data that you're saving contains numbers at the end "length1", "length2", etc. You need to remove those numbers.

Upvotes: 1

Related Questions