簡體   English   中英

更新 mongoose 文檔中的數組

[英]Update an array in document in mongoose

下面的架構:

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

    
} )

我想要做的是獲取來自正文的答案字符串並使用它來更新數組。 下次我這樣做時,我希望將該元素附加到數組中。

嘗試這個:

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


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM