在postjs post route中我将mongoose模型对象保存到一个数组中,现在我想将该数组保存到mongodb,为了做到这一点,我需要调用array.save()方法,这是方法中构建的mongoose。为此,我需要将此数组转换为本例中 Form 的Mongoose模型类型。请告诉我们如何应用此转换,还是需要其他解决方案? Mongoose架构是:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var formSchema = new Schema({
controlType: {type: String, required: true},
label: {type: String, required: true},
required: {type: Boolean},
placeholder: {type: String},
options: [String], //to store options for select or radio input
} , {collection: 'inputForm'});
module.exports = mongoose.model('Form', formSchema);
NodeJS发布路线:
router.post('/userform', function (req, res, next) {
var form = [];
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
var formObj = new Form({
controlType: req.body[key].controlType,
label: req.body[key].label,
required: req.body[key].required,
placeholder: req.body[key].placeholder,
options: req.body[key].options
});
}
form.push(formObj);
}
console.log('type of form 0528');
console.log(typeof(form));
form.save(function(err, result) { // here is the issue, this line is not working because form is not type of mongoose model
if (err) {
return res.status(500).json({
title: 'An error occurred in form api 0528',
error: err
});
}
res.status(201).json({
message: 'Form created',
obj: result
});
});
});
module.exports = router;
答案 0 :(得分:1)
Model.create 可以使用一组对象来创建多个文档。
因此,您可以构建一个对象数组而不是模型实例,然后将该数组传递给 Form.create :
var formArr = []
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
var formObj = {
controlType: req.body[key].controlType,
label: req.body[key].label,
required: req.body[key].required,
placeholder: req.body[key].placeholder,
options: req.body[key].options
}
formArr.push(formObj)
}
}
Form.create(formArr, function(err, results) {
...
})
如果要在单个文档中保存对象数组,请尝试使用嵌套模式:
var controlSchema = new Schema({
controlType: {type: String, required: true},
label: {type: String, required: true},
required: {type: Boolean},
placeholder: {type: String},
options: [String]
}, {collection: 'inputForm'})
var formSchema = new Schema({
controls: [controlSchema]
})
module.exports = mongoose.model('Form', formSchema)
...然后将数组保存为新文档中的控件字段,如下所示:
var controlsArr = []
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
var controlObj = {
controlType: req.body[key].controlType,
label: req.body[key].label,
required: req.body[key].required,
placeholder: req.body[key].placeholder,
options: req.body[key].options
}
controlsArr.push(controlObj)
}
}
var form = new Form({
controls: controlsArr
})
form.save(function(err, result) {
...
})