javascript - How to save form data as an objects and array of objects to mongodb using loop in node.js? -
i new mongodb, using node.js, express 4 , mongoose(mongodb) project.i stuck save form info mongodb within loop , model contains objects , array of objects well.
model :
var subscriber = new schema({ first_name: string, emergency_contact_1: { name: string, number: [{ type: string }] }, residential: { phone: string, address: string, ... }, medications: [ { visit_id: { type: object }, name: string, .... }], food_allergies: [ {type: string} ], .... });
controller : want save info in way:
var subscriber = new subscriber(); //here trying save form's fields mongobd fields. (var field in form_data) { subscriber[field] = form_data[field]; } subscriber.save(function (err1, instance) { if (err) { console.log("error"); homecoming res.send("..."); } console.log("saved successfully"); }
normal fields getting saved using above loop when objects or arrays came won't save mongodb.
any solution ? or other way insert/save info through loop mongodb model ? help appreciated.thank you..!!
nodejs
var personschema = new schema({ name: { given: { type: string, required: true }, family: { type: string, required: true } }, children: [personschema] }); var person = mongoose.model('person', personschema); app.post('/person', function (req, res) { person.create(req.body) .then(function (created) { console.log(created); res.json(created.id); }); });
client
$.ajax({ url: '/person', type: 'post', data: { name: { family: 'green' }, children: [{ name: { given: 'matt', family: 'green' } }, { name: { given: 'dave', family: 'green' } }] } })
as can see, have nested objects , arrays. works fine me :)
javascript node.js mongodb express mongoose
No comments:
Post a Comment