【发布时间】:2018-11-22 11:35:04
【问题描述】:
所以我正在构建这个允许用户发布 cmets 的应用程序。
我遇到了一个问题,当我尝试发表评论时,它实际上并没有添加到已经存在的评论中,它只是替换了已经存在的评论。我不确定发生了什么问题。
这是我的评论快速路线:
.put((req, res) => {
Issue.findByIdAndUpdate(req.params.id, req.body, {$push: {comments: req.body.comments}}, (err, updatedComment) => {
if(err) return res.status(500).send(err);
return res.send(updatedComment);
})
})
这是我的 Redux,当我编辑帖子以添加 cmets 时,我实际上使用的是相同的操作创建器:
export const getIssues = () => {
return dispatch => {
axios.get("/issues").then(response => {
dispatch({
type: "GET_ISSUES",
issues: response.data
})
}).catch(err => {
console.log(err);
})
}
}
export const editIssue = (editedIssue, id) => {
return dispatch => {
axios.put(`/issues/${id}`, editedIssue).then(response => {
dispatch(getIssues());
}).catch(err => {
console.log(err);
})
}
}
const reducer = (state = [], action) => {
switch(action.type){
case "GET_ISSUES":
return action.issues
default:
return state
}
}
这是添加评论的表单和 onClick 方法:
addComment = () => {
this.props.editIssue({
comments: this.state.comment
}, this.props.id)
}
<button onClick={this.toggleComment}>Add A Comment</button>
{this.state.isCommenting ? <form>
<input type="text" value={this.state.comment} name="comment" placeholder="Add A Comment..." onChange={this.handleChange}/>
<button onClick={this.addComment}>Submit</button>
</form>: null}
最后是我的帖子架构:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const issuesSchema = new Schema({
issue: {
type: String,
required: true
},
description: {
type: String,
required: true,
},
comments: [String]
})
module.exports = mongoose.model("Issues", issuesSchema);
如果您想查看我的代码中的其他内容,请告诉我。我故意省略了一些代码,因为我觉得这篇文章已经很长了。
【问题讨论】:
-
Issue.findByIdAndUpdate(req.params.id, {$push: {comments: req.body.comments}}, (err, updatedComment) =>你也有req.body在那里它没有这样的地方。如果您想“覆盖”所有内容,则只需包含req.body。如果您想“添加到 cmets”,则只需使用$push通过 cmets -
您要发布多个 cmets 吗?我的意思是
req.body.comments是 cmets 数组吗? -
@FarhanTahir 它一开始是一个空数组。当我第一次尝试添加评论时,它可以工作,评论被添加到数组中,但是当我尝试添加另一个评论时,它实际上并没有添加到数组中,它只是替换了第一个评论。所以本质上,我只能发表一条评论,否则它只会替换已有的内容。
标签: javascript mongodb reactjs mongoose redux