【问题标题】:Update an array in document in mongoose在猫鼬中更新文档中的数组
【发布时间】:2021-06-30 06:15:44
【问题描述】:

下面的架构:

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));

    
} )

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

【问题讨论】:

标签: node.js reactjs mongodb mongoose backend


【解决方案1】:

试试这个:

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


【讨论】:

    猜你喜欢
    • 2012-02-15
    • 2015-04-21
    • 2022-08-18
    • 2021-03-09
    • 2015-04-07
    • 2020-08-05
    • 2015-06-03
    • 2020-10-18
    • 2016-05-24
    相关资源
    最近更新 更多