Node.js 无法在Mern stack app中使用axios.put更新mogodb对象
我需要从我的mongodb数据库“comments”集合更新我的“comment”对象。更具体地说,当我按下“Like”按钮时,我想用axios发送一个put请求,在这里我可以从“comment”对象向“likes”添加+1 所有其他操作都很正常(获取评论、添加评论等),唯一让我头疼的是更新评论 如果有人能帮忙,我将不胜感激。提前谢谢 在这里,我添加了我的代码: //--------CommentComponent.jsNode.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 }
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)
我改变了一些事情:
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))
}
}
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))
}
}
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_注释,因此也没有减速器
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))
}
}