[英]Update an array in document in mongoose
The schema below:下面的架构:
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
}
})
The code below:下面的代码:
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));
} )
What I want to do is take the answer string that is coming from the body and use it to update the array.我想要做的是获取来自正文的答案字符串并使用它来更新数组。 And the next time I do this I want that element to be appended to the array.下次我这样做时,我希望将该元素附加到数组中。
Try this:尝试这个:
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.