我是MongoDB的新手,我正在为我的项目使用Node.js,Express 4和mongoose(mongoDB)。我坚持在循环中将表单数据保存到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 :(得分: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'
}
}]
}
})
如您所见,我有嵌套的对象和数组。这适合我:)