尝试删除评论并最终删除帖子而不是使用REACT / NODE / EXPRESS / MONGODB评论

时间:2017-07-03 18:06:12

标签: javascript node.js mongodb reactjs express

这里的问题是我试图删除评论,而是删除它所属的帖子。我已经检查过以确保我没有在某个地方调用错误的功能,但我似乎无法找到我。我不确定前端或后端的编码是否错误。

我将代码与服务器和客户端分开,并尝试明确说明了什么。我正在使用前端的反应和我的后端的node / express / mongodb。

正如我通常所做的那样,如果您要求更多信息或者希望我尝试控制日志,我会将其放入编辑中,这样评论就不会变得拥挤,其他人也会更容易看到。

修改:添加了帖子reducer和comments reducer。

客户端:

评论显示页面:

我按下删除按钮,该按钮调用调用deleteComment函数的onClick事件处理程序。我有控制台记录了函数中的所有信息,以确保一切都是我想要的。

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

deleteComment的行动:

我也在这里记录了所有内容。正如你所见,一切都正确地传递过来。

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

服务器

路线:

app.delete('/posts/:id/comments/:comment_id', requireAuth, Comments.deleteComment);

控制器:

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}`)
    }
  })
}

评论模型:

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

帖子型号:

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;

我如何填写帖子中的评论:

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

帖子缩减器:

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

评论减速机:

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

0 个答案:

没有答案