更新猫鼬文档中的数组

时间:2021-04-03 19:33:31

标签: node.js reactjs mongodb mongoose backend

架构如下:

const questionSchema = new Schema({
    askedBy: {
        type: String,
        required: true
    },
    title:{
        type:String,
        required: true
    },
    queryType: {
        type: String,
        required: true
    },
    question:{
        type: String,
        required:true
    },
    datePosted: String,
    isOpen: Boolean,
    answers:{
        type:Array
    }
})

代码如下:

app.patch("/:id" , (req,res) =>{
        
       Question.findByIdAndUpdate(req.params.id, {answer:[req.body.answer]}, {new:true})
         .then((response) => res.json(response))
         .catch((err) => res.json(err));

    
} )

我想要做的是获取来自正文的答案字符串并用它来更新数组。 下次我这样做时,我希望将该元素附加到数组中。

1 个答案:

答案 0 :(得分:1)

试试这个:

Question.findByIdAndUpdate(req.params.id, {
   $push: {
       answer: req.body.answer
   }, {new:true})
.then((response) => res.json(response))
.catch((err) => res.json(err));