2014-10-09 84 views
3

我是MongoDB的新手,我爲我的項目使用了Node.js,Express 4和mongoose(mongoDB)。我堅持將表單數據保存到循環中的mongoDB中,我的模型也包含對象和對象數組。如何使用node.js中的循環將表單數據作爲對象和對象數組保存到mongodb中?

型號

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

控制器
我想用這種方式保存數據:使用上述循環

var subscriber = new Subscriber(); 

//Here I am trying to save all form's fields to mongoBD fields. 
for (var field in form_data) { 
    subscriber[field] = form_data[field]; 
} 

subscriber.save(function (err1, instance) { 
    if (err) { 
     console.log("error"); 
     return res.send("..."); 
    } 
    console.log("saved successfully"); 
} 

普通領域越來越正確保存,但是當對象或數組來了,它不會保存到mongoDB。

任何解決方案?或者通過循環向mongoDB模型插入/保存數據的其他方式?
任何幫助將不勝感激。謝謝.. ..!

+0

你嘗試使用'Subscriber.create(form_data,callback)'? – 2014-10-09 21:50:19

+0

@AndrewVolchenko我已經嘗試過,並且對於像first_name,Last_name和all.nbsp但單獨的字段工作正常,但在mongoDB模型中我有對象和對象數組,因此當時它沒有得到保存,因爲form_data將作爲individual.For例如,我怎樣才能保存form_data像first_name,residential_phone,residential_address mongoDB模型,如first_name:'',residential:{phone:'',address:''} using loop?謝謝..!! – Divyesh 2014-10-10 06:28:14

回答

0

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

客戶

$.ajax({ 
    url: '/person', 
    type: 'POST', 
    data: { 
     name: { 
      family: 'Green' 
     }, 
     children: [{ 
      name: { 
       given: 'Matt', 
       family: 'Green' 
      } 
     }, { 
      name: { 
       given: 'Dave', 
       family: 'Green' 
      } 
     }] 
    } 
}) 

正如你所看到的,我有嵌套對象和數組。這對我工作正常:)

+0

你能告訴我那個req.body包含什麼嗎?如果它包含來自客戶端的數據,那麼它不會爲我工作。因爲在我的代碼中,form_data包含單個字段的值不是object.and如果不是,則給出它的一個片段。謝謝。 – Divyesh 2014-10-10 12:50:46

+0

@Divyesh你能否提供你的'form_data'對象的expample? – 2014-10-10 14:35:15

+0

我的form_data對象看起來像{first_name:'divyesh',last_name:'dhokiya',resi_phone:'8147181480',resi_address,ec1_name:'abc',ec1_phone:'1234567890'}和mongodb模型就像上面我提到的問題。謝謝你.. !! – Divyesh 2014-10-10 16:01:12

相關問題