Node.js 无法在Mern stack app中使用axios.put更新mogodb对象

Node.js 无法在Mern stack app中使用axios.put更新mogodb对象,node.js,reactjs,mongodb,express,mern,Node.js,Reactjs,Mongodb,Express,Mern,我需要从我的mongodb数据库“comments”集合更新我的“comment”对象。更具体地说,当我按下“Like”按钮时,我想用axios发送一个put请求,在这里我可以从“comment”对象向“likes”添加+1 所有其他操作都很正常(获取评论、添加评论等),唯一让我头疼的是更新评论 如果有人能帮忙,我将不胜感激。提前谢谢 在这里,我添加了我的代码: //--------CommentComponent.js import React, { useState, useEffect }

我需要从我的mongodb数据库“comments”集合更新我的“comment”对象。更具体地说,当我按下“Like”按钮时,我想用axios发送一个put请求,在这里我可以从“comment”对象向“likes”添加+1

所有其他操作都很正常(获取评论、添加评论等),唯一让我头疼的是更新评论

如果有人能帮忙,我将不胜感激。提前谢谢

在这里,我添加了我的代码:

//--------CommentComponent.js

import React, { useState, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { getComments, updateComment } from '../actions/commentActions'

const PostPage = ({ match }) => {
    
const commentz = useSelector(store => store.comment.comments)
const dispatch = useDispatch()

useEffect(() => {
    dispatch(getComments())
}, [dispatch])

const handleLike = e => {
    dispatch(updateComment(e.target.id))
}

return (
    {commentz ? commentz.map(comm => 
        comm.forWich === match.params.id ?
            <div key={comm._id} className={styles.comment}>
                <div>
                    <h2>{comm.name}</h2>
                </div>
                <div>
                     <p>{comm.comment}</p>
                </div>
                     {comm.likes} <button id={comm} onClick={handleLike}>Like</button>
                <div>
            </div>
        : null
    ) : null}
    )
}

export default PostPage
//-------comments.js

const express = require('express');
const router = express.Router();

// Comments Model
const Comment = require('../../models/Comment');

// @route UPDATE api/comments
// @desc Update comment
// @access Public
router.put('/:id', (req, res, next) => {
    Comment.findbyId(req.params.id)
       .then(comment => comment.update(req.body))
       .catch(next);
})

module.exports = router;
//--------CommentActions.js

import axios from 'axios';
import { 
    GET_COMMENTS,
    ADD_COMMENTS,
    COMMENTS_LOADING,
    GO_COMMENTS,
    UPDATE_COMMENTS
} from './types';



export const updateComment = comment => {
    return function(dispatch) {
        axios
            .put(`/api/comments`, comment)
            .then(res =>
                dispatch({
                    type: UPDATE_COMMENTS,
                    payload: comment
                })
            )
    }
}
//--------CommentReducer.js

import {
    GET_COMMENTS,
    ADD_COMMENTS,
    COMMENTS_LOADING,
    GO_COMMENTS,
    UPDATE_COMMENTS
} from '../actions/types';

const initialState = {
    comments: []
}

export default function(state = initialState, action) {
    switch(action.type) {
        case UPDATE_COMMENTS:
            return {
                ...state,
                comments: state.comments.map(comm => comm._id === action.payload._id ? comm.likes = action.payload + 1 : comm.likes)
    }
}
}
您需要使用:

Comment.findById()

您对客户端的put请求需要类似于:

axios.get(`/api/comments/${comment.id}` comment)


我改变了一些事情:

  • 注释模型“likes”变成了一个对象数组,因此我可以存储注释的Id、喜欢注释的访客Id(在本地存储的帮助下,将在页面加载时创建该Id)以及单击like按钮的日期:
  • models/Comment.js:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    // Create Schema
    const CommentSchema = new Schema({
        likes: [
            {
                commentId: {
                    type: String,
                    required: true
                },
                userId: {
                    type: String,
                    required: true
                },
                date: {
                    type: Date,
                    default: Date.now
                }
            }
        ],
        name: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true
        },
        comment: {
            type: String,
            required: true
        },
        forWich: {
            type: String,
            required: true
        },
        date: {
            type: Date,
            default: Date.now
        }
    });
    
    module.exports = Comment = mongoose.model('comment', CommentSchema);
    
    router.post('/like', (req, res) => {
        const { commentId, userId } = req.body;
        Comment.findById(commentId)
        .then(comment => {
            comment.likes.unshift({ commentId, userId });
            comment.save().then(comment => res.json(comment));
    
        })
        .catch(err => {
            res.status(404).json({ commentnotfound: "No comment found" })
        });
    });
    
    export const addLike = ({ commentId, userId }) => {
        return function(dispatch) {
            const config = {
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            const body = JSON.stringify({ commentId, userId });
    
            axios.post(`/api/comments/like`, body, config)
                .then(res => {
                    dispatch(getComments())
                }
            )
        }
    };
    
    useEffect(() => {
        if (!localStorage.getItem(`userId`)) {
            localStorage.setItem(`userId`, uuidv4())
        }
    }, [])
    
    const handleLike = e => {
        e.preventDefault()        
        if(localStorage.getItem(`userId`)) {
            const newLike = {
                commentId: e.target.value,
                userId: localStorage.getItem(`userId`)
            }
            dispatch(addLike(newLike))
        }
    }
    
  • 路由已更改,从“put”改为“post”,因此我添加了一个完整的对象,而不是串联一个数字:
  • 路由/api/评论:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    // Create Schema
    const CommentSchema = new Schema({
        likes: [
            {
                commentId: {
                    type: String,
                    required: true
                },
                userId: {
                    type: String,
                    required: true
                },
                date: {
                    type: Date,
                    default: Date.now
                }
            }
        ],
        name: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true
        },
        comment: {
            type: String,
            required: true
        },
        forWich: {
            type: String,
            required: true
        },
        date: {
            type: Date,
            default: Date.now
        }
    });
    
    module.exports = Comment = mongoose.model('comment', CommentSchema);
    
    router.post('/like', (req, res) => {
        const { commentId, userId } = req.body;
        Comment.findById(commentId)
        .then(comment => {
            comment.likes.unshift({ commentId, userId });
            comment.save().then(comment => res.json(comment));
    
        })
        .catch(err => {
            res.status(404).json({ commentnotfound: "No comment found" })
        });
    });
    
    export const addLike = ({ commentId, userId }) => {
        return function(dispatch) {
            const config = {
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            const body = JSON.stringify({ commentId, userId });
    
            axios.post(`/api/comments/like`, body, config)
                .then(res => {
                    dispatch(getComments())
                }
            )
        }
    };
    
    useEffect(() => {
        if (!localStorage.getItem(`userId`)) {
            localStorage.setItem(`userId`, uuidv4())
        }
    }, [])
    
    const handleLike = e => {
        e.preventDefault()        
        if(localStorage.getItem(`userId`)) {
            const newLike = {
                commentId: e.target.value,
                userId: localStorage.getItem(`userId`)
            }
            dispatch(addLike(newLike))
        }
    }
    
  • 重复操作,我将“handleLike”改为“addLike”
  • actions/commentActions.js:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    // Create Schema
    const CommentSchema = new Schema({
        likes: [
            {
                commentId: {
                    type: String,
                    required: true
                },
                userId: {
                    type: String,
                    required: true
                },
                date: {
                    type: Date,
                    default: Date.now
                }
            }
        ],
        name: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true
        },
        comment: {
            type: String,
            required: true
        },
        forWich: {
            type: String,
            required: true
        },
        date: {
            type: Date,
            default: Date.now
        }
    });
    
    module.exports = Comment = mongoose.model('comment', CommentSchema);
    
    router.post('/like', (req, res) => {
        const { commentId, userId } = req.body;
        Comment.findById(commentId)
        .then(comment => {
            comment.likes.unshift({ commentId, userId });
            comment.save().then(comment => res.json(comment));
    
        })
        .catch(err => {
            res.status(404).json({ commentnotfound: "No comment found" })
        });
    });
    
    export const addLike = ({ commentId, userId }) => {
        return function(dispatch) {
            const config = {
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            const body = JSON.stringify({ commentId, userId });
    
            axios.post(`/api/comments/like`, body, config)
                .then(res => {
                    dispatch(getComments())
                }
            )
        }
    };
    
    useEffect(() => {
        if (!localStorage.getItem(`userId`)) {
            localStorage.setItem(`userId`, uuidv4())
        }
    }, [])
    
    const handleLike = e => {
        e.preventDefault()        
        if(localStorage.getItem(`userId`)) {
            const newLike = {
                commentId: e.target.value,
                userId: localStorage.getItem(`userId`)
            }
            dispatch(addLike(newLike))
        }
    }
    
    …正如您所看到的,没有任何类型的有效负载,因此不再需要使用UPDATE_注释,因此也没有减速器

  • 最后是前端,在页面加载时,我使用localStorage为新客户机分配Id。基于该Id,我正在创建一个新的相似对象:
  • PostPage.js:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    // Create Schema
    const CommentSchema = new Schema({
        likes: [
            {
                commentId: {
                    type: String,
                    required: true
                },
                userId: {
                    type: String,
                    required: true
                },
                date: {
                    type: Date,
                    default: Date.now
                }
            }
        ],
        name: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true
        },
        comment: {
            type: String,
            required: true
        },
        forWich: {
            type: String,
            required: true
        },
        date: {
            type: Date,
            default: Date.now
        }
    });
    
    module.exports = Comment = mongoose.model('comment', CommentSchema);
    
    router.post('/like', (req, res) => {
        const { commentId, userId } = req.body;
        Comment.findById(commentId)
        .then(comment => {
            comment.likes.unshift({ commentId, userId });
            comment.save().then(comment => res.json(comment));
    
        })
        .catch(err => {
            res.status(404).json({ commentnotfound: "No comment found" })
        });
    });
    
    export const addLike = ({ commentId, userId }) => {
        return function(dispatch) {
            const config = {
                headers: {
                    'Content-Type': 'application/json'
                }
            }
            const body = JSON.stringify({ commentId, userId });
    
            axios.post(`/api/comments/like`, body, config)
                .then(res => {
                    dispatch(getComments())
                }
            )
        }
    };
    
    useEffect(() => {
        if (!localStorage.getItem(`userId`)) {
            localStorage.setItem(`userId`, uuidv4())
        }
    }, [])
    
    const handleLike = e => {
        e.preventDefault()        
        if(localStorage.getItem(`userId`)) {
            const newLike = {
                commentId: e.target.value,
                userId: localStorage.getItem(`userId`)
            }
            dispatch(addLike(newLike))
        }
    }