【问题标题】:How to post request for a particular field of array in mern stack如何在 mern 堆栈中发布对特定数组字段的请求
【发布时间】:2021-12-09 08:13:30
【问题描述】:

代码没有在答案数组中添加答案......请解释如何编写正确的方法来实现它? 'id' 是问题,用于参数。

架构:

const QuestionSchema = new mongoose.Schema({
    qtitle:{
        type:String,
        required:true
    },
    descofq:{
        type:String,
        required:true
    },
    pic:{
        type:String,
        default:"no photo"
    },
    answers:[
        {
            answer:{
                type:String,
                required:false
            },
            picofa:{
                type:String,
                default:"no photo"
            },
            postedBy:{
                type:mongoose.Schema.Types.ObjectId,
                ref:"USER"
            }
        }
    ]
    }
})

POST 请求:

router.post('/answer/:id',authenticate,(req,res)=>{
    Question.findById(req.params.id).then(question=>{
        question.answers.answer = req.body.answer;
        question.save().then(result=>{
            res.json(result)
        }).catch(err=>{
            res.status(400).send(err);
        })
    }).catch(err=>{
        res.status(200).send(err);
    })
})

我也试过 question.answers.answer.push(answer); 括号中的答案将从 req.body 获取,但这也不起作用。

【问题讨论】:

    标签: mongodb express mongoose mongoose-schema mern


    【解决方案1】:

    您的答案是一个数组。您不能将值设置为对象。 如果要将对象添加到数组中。让我们使用推送功能。

    例如: question.answers.push({ answer: req.body.answer, postedBy: “userId” }); 问题.save()

    【讨论】:

    • 用过但没用
    • 你必须添加一个对象。因为在架构中您定义的答案是嵌套字段。您不能将字符串推送到它
    【解决方案2】:

    Answers 字段是一个数组,您应该指定哪个答案 里面的答案数组

    router.post('/answer/:id',authenticate,(req,res)=>{
        Question.findById(req.params.id).then(question=>{
            question.answers.push(req.body.answers);
            question.save().then(result=>{
                res.json(result)
            }).catch(err=>{
                res.status(400).send(err);
            })
        }).catch(err=>{
            res.status(200).send(err);
        })
    })
    

    Example: req.body.answers = { answer: "bla bla..", picofa: "bla bla", postedBy: userId }

    另一种解决方案:

    router.post('/answer/:id',authenticate,(req,res)=>{
        Question.findById(req.params.id).then(question=>{
            question.answers[0].answer = req.body.answer;
            question.save().then(result=>{
                res.json(result)
            }).catch(err=>{
                res.status(400).send(err);
            })
        }).catch(err=>{
            res.status(200).send(err);
        })
    })
    

    【讨论】:

    • 你能解释一下示例部分吗,比如我应该在哪里写,我应用了它但它不起作用
    • 这里的例子是关于你应该从客户端发送的请求(如邮递员)
    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 2020-11-28
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2018-09-20
    相关资源
    最近更新 更多