【问题标题】:Form for submitting multiple fields提交多个字段的表单
【发布时间】:2021-05-18 00:18:32
【问题描述】:

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

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 个字段中停止此操作

【问题讨论】:

    标签: node.js arrays mongodb mongoose backend


    【解决方案1】:

    将其停在 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)
        })
    ...
    

    【讨论】:

    • @hereforadoubt 太棒了。如果对您有帮助,请不要忘记接受答案。
    猜你喜欢
    • 2016-01-20
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多