Javascript 将数组类型转换为Mongoose模型
在nodejs post route中,我将mongoose模型对象保存到一个数组中。现在,我想将该数组保存到mongodb中,为此,我需要调用array.save方法,它是mongoose内置的方法。为此,我需要将此数组转换为Mongoose模型类型,即本例中的表单。请告诉我如何应用此转换,或者我是否需要任何其他解决方案? 猫鼬模式是: NodeJS邮政路线: Model.create可以使用一组对象来创建多个文档 因此,您可以构建对象数组而不是模型实例,然后将该数组传递给Form.create: 如果要在单个文档中保存对象数组,请尝试使用嵌套架构:Javascript 将数组类型转换为Mongoose模型,javascript,node.js,mongoose-schema,Javascript,Node.js,Mongoose Schema,在nodejs post route中,我将mongoose模型对象保存到一个数组中。现在,我想将该数组保存到mongodb中,为此,我需要调用array.save方法,它是mongoose内置的方法。为此,我需要将此数组转换为Mongoose模型类型,即本例中的表单。请告诉我如何应用此转换,或者我是否需要任何其他解决方案? 猫鼬模式是: NodeJS邮政路线: Model.create可以使用一组对象来创建多个文档 因此,您可以构建对象数组而不是模型实例,然后将该数组传递给Form.creat
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) {
...
})
但我想将其存储为一个包含对象数组的文档,而不是存储在单独的文档中@Steve HolgadoSo您想要一个包含表单子文档数组的文档吗?在这种情况下,您将需要一个带有数组字段的模式,该字段包含与您所拥有的类似的对象。我已使用一个解决方案更新了我的答案,该解决方案使用嵌套模式将数组保存到单个文档中。我希望这会有帮助。是的,它成功了,非常感谢。从你的回答中我学到了很多知识。你可以使用Form.findOne和查询来查找文档,如果你知道文档的_id,也可以使用Form.findById。否则,您可以使用Form.find{}、functionerr、docs{…}查找所有文档,然后处理返回的文档,以查找要在路由响应中返回的文档。
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) {
...
})