问题
The problem here is that I am trying to delete a comment and instead it deletes the post it belongs too. I have checked to make sure I am not calling the wrong function somewhere, but I can't seem to find that I am. I am not sure if this is wrong coding on the front or back-end.
I will separate the code from server and client and also try to make it clear what does what. I am using react for front side and node/express/mongodb for my back-end.
As I usually do if you request more information or want me to try to console log something I will put it in an edit so the comments do not get crowded and it will be easier for others to see.
Edit: Added posts reducer and comments reducer.
Client:
Comment show page:
I am pressing the delete button which calls an onClick event handler that calls the deleteComment function. I have console logged all the information inside the function to make sure everything is what I want it to be.
renderCommentsButtons(comment) {
const { post, user, auth } = this.props;
if(!user) {
return (<div></div>);
}
if(auth) {
if(user._id === comment.author.id) {
return (
<div>
<button
onClick={() => this.deleteComment(comment)}
className="btn btn-xs btn-danger">
Delete
</button>
<Link
to={`/posts/${post._id}/comments/${comment._id}/edit`}
className="btn btn-xs btn-warning">
Edit
</Link>
</div>
)
}
}
}
renderComments() {
const { post } = this.props;
return post.comments.map((comment) => {
return (
<li className="list-group-item" key={comment._id}>
<div>
{comment.text} : {comment.author.email}
</div>
{this.renderCommentsButtons(comment)}
</li>
);
});
}
deleteComment(comment) {
const {id} = this.props.match.params;
const {user, post, auth} = this.props;
if(!user) {
return (<div></div>);
}
if(auth) {
if(user._id === comment.author.id){
this.props.deleteComments(id, comment._id, () => {
this.props.history.push(`/posts/${post._id}`);
});
}
}
}
Action for deleteComment:
I have logged everything here as well. Everything is being passed through correctly as you can see.
export function deleteComments(post_id, comment_id, cb) {
return function(dispatch) {
console.log('post_id:', post_id, 'comment_id:', comment_id);
axios.delete(`${ROOT_URL}/${post_id}/comments/${comment_id}`)
.then(() => {
dispatch({
type: DELETE_COMMENTS,
payload: comment_id
});
})
.then(() => cb())
.catch((error) => {
console.log(error);
});
}
}
Server:
Route:
app.delete('/posts/:id/comments/:comment_id', requireAuth, Comments.deleteComment);
Controller:
exports.deleteComment = function(req, res, next) {
Comments.findByIdAndRemove(req.params.comment_id, function(err) {
if(err) {
return next(err);
} else {
res.redirect(`/posts/${req.params.id}`)
}
})
}
Comments Model:
var mongoose = require("mongoose");
const Schema = mongoose.Schema;
var commentSchema = new Schema({
text: String,
createdAt: {type: Date, default: Date.now },
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
email: String
}
});
module.exports = mongoose.model("comments", commentSchema);
Posts Model:
var mongoose = require("mongoose");
const Schema = mongoose.Schema;
var postsSchema = new Schema({
title: String,
createdAt: {type: Date, default: Date.now},
content: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "user"
},
email: String
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "comments"
}
]
});
var Posts = mongoose.model("posts", postsSchema);
module.exports = Posts;
How I populate the comments inside post:
exports.getOnePost = function(req, res, next) {
Posts.findById(req.params.id).populate("comments").exec(function(err, foundPost) {
if(err) {
return next(err);
} else {
res.json(foundPost);
}
});
}
Posts Reducer:
import {
GET_ALL_POSTS,
GET_POST,
CREATE_POST,
DELETE_POST,
UPDATE_POST
} from '../actions/types';
import _ from 'lodash';
export default function(state = {}, action) {
switch(action.type) {
case GET_ALL_POSTS:
return _.mapKeys(action.payload.data, '_id');
break;
case GET_POST:
return {...state, [action.payload.data._id]: action.payload.data};
break;
case DELETE_POST:
return _.omit(state, action.payload);
break;
case UPDATE_POST:
let updates = {[action.payload.data._id]: action.payload.data}
return _.merge(...state, updates);
break;
default:
return state;
break;
}
}
Comments Reducer:
import {
GET_COMMENTS,
CREATE_COMMENTS,
DELETE_COMMENTS,
UPDATE_COMMENTS
} from '../actions/types';
import _ from 'lodash';
export default function(state={}, action) {
switch(action.type) {
case GET_COMMENTS:
return _.mapKeys(action.payload.data, '_id');
break;
case CREATE_COMMENTS:
return {...state, [action.payload.data._id]: action.payload.data};
break;
case DELETE_COMMENTS:
return _.omit(state, action.payload);
break;
case UPDATE_COMMENTS:
let updates = {[action.payload.data._id]: action.payload.data}
return _.merge(...state, updates);
break;
default:
return state;
break;
}
}
来源:https://stackoverflow.com/questions/44891664/trying-to-delete-comments-and-end-up-deleting-post-and-not-comment-using-react-n