繁体   English   中英

提交多个字段的表单

[英]Form for submitting multiple fields

我想创建一个包含 10 个标题、10 个正文和 10 个图像的表单。 像 Instagram 一样,但每张照片的标题都不同。 我想将它插入到每个数组中。 包含 10 个标题的标题数组、文章每个部分的正文数组等。 在 model 模式中,我创建了一个这样的数组:

const postSchema = new mongoose.Schema({
    title:[{
        type:String,
        required:true
    }],
    body:[{
        type:String,
        required:true
    }],
    photo:[{
        type:String,
        require:false
    }],
    postedBy:{
        type:ObjectId,
        ref:'User'
    }
})
mongoose.model('Post',postSchema)

在路由文件中

router.post('/createpost',requireLogin,(req,res)=>{
    const {title=[],body=[],pic=[]} = req.body 
    if(!title[0] || !body[0]){ //atleast 1 body and 1 title should be present
    return  res.status(422).json({error:"Please add all the fields"})
    }
    
    const post = new Post({
        title[],
        body[],
        photo:pic[],
        postedBy:req.user
    })
    post.save()
    .then(result=>{
        res.json({post:result})
    })
    .catch(err=>{
        console.log(err)
    })
})

但这肯定不对另外,如何仅在 10 个字段中停止此操作

将其停在 10 个字段更像是一个前端问题。 这个:

title:[{
        type:String,
        required:true
    }]

将允许您输入无限的字符串数组。

现在,至于保存你的标题、身体和图片,你真的很接近了。 只需将您的代码更改为:

...
const post = new Post({
        title,
        body,
        photo:pic,
        postedBy:req.user
    })
    post.save()
    .then(result=>{
        res.json({post:result})
    })
    .catch(err=>{
        console.log(err)
    })
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM