I have created a form where i have certain fields.I also have a field that contains an array of fields within."req.body.lead" output of the field is as:
// output of console.log("req.body.lead",req.body.lead);
business_address_attributes:
{ address_type: 'Business',
street1: 'Street 1...',
street2: 'Street 2...',
city: 'City...',
state: 'State...',
zipcode: 'Zip Code...',
country: '' },
I can store the entire object inside another object as:
var address = new Addresses(req.body.lead.business_address_attributes);
Inside mongodb i have declared a field as:
business_address_attributes : [Addresses],
//Note: [Addresses] refers to address class
Now when i try to store the inside monogdb using following, I am getting error,unable to save lead
var lead = new Leads(req.body.lead);
var address = new Addresses(req.body.lead.business_address_attributes);
lead.business_address_attributes.$push(address);
lead.save();
// console.log(lead.business_address_attributes) now gives following output:
[ { address_type: 'Business',
street1: 'Street 1...',
street2: 'Street 2...',
city: 'City...',
state: 'State...',
zipcode: 'Zip Code...',
country: '',
_id: 4f857a2e491383dc64000008 } ]
I don't know how to solve the problem.Can someone help.
My solution of this problem was to declare the field with array of documents as a reference array.
Create a schema for Address
document:
var AddressSchema = new Schema({
//attributes
});
and create a model:
mongoose.model('address', AddressSchema)
Now in the parent document you can say
business_address_attributes : [{ type: Schema.ObjectId, ref: 'address' }]
When creating a new document, create Address document first, save it, get ID of a saved doc and push it into lead.business_address_attributes
.
To get back a document with addresses instead of just IDs, use mongoose's populate('business_address_attributes')
method.