简体   繁体   English

MongoDB 不断返回比预期值少一个值

[英]MongoDB keeps returning one less value than intended value

I am currently working on a blog project where I have to enable a "liking" feature on my blog website.我目前正在做一个博客项目,我必须在我的博客网站上启用“喜欢”功能。 I have enabled the liking feature, however, whenever I test the liking feature with my MongoDB, the response I get is always a like that is one less than the intended value.我已经启用了点赞功能,但是,每当我用我的 MongoDB 测试点赞功能时,我得到的响应总是比预期值小一个。 For example, if I give a blog a like, that already has 4 likes, I get back a document only showing the 4 likes and not the updated document with the new 5 likes.例如,如果我给一个已经有 4 个赞的博客点赞,我会返回一个仅显示 4 个赞的文档,而不是包含新的 5 个赞的更新文档。

Here is my frontend code that deals with the "liking" feature:这是我处理“喜欢”功能的前端代码:

import axios from "axios"
import { useEffect, useState } from "react"
import blogService from '../services/blogs'
const baseUrl = '/api/blogs'

const Blog = ({blog}) => {
  const [checker, setChecker] = useState(false)
  const [blogLikes, setBlogLikes] = useState(0)
  const [updatedBlog, setUpdatedBlog] = useState({})
  const buttonText = checker  ? 'hide' : 'view'

  useEffect(() => {
    setUpdatedBlog({
      user: blog.user?.id,
      likes: blogLikes,
      author: blog.author,
      title: blog.title,
      url: blog.url
    })
  }, [blogLikes])
  
  
  const blogStyle = {
    paddingTop: 10,
    paddingLeft: 2,
    border: 'solid',
    borderWidth: 1,
    marginBottom: 5
  }

  const handleLike = async (e) => {
    e.preventDefault()

    setBlogLikes(blogLikes + 1)
    
    const response = await blogService.update(blog?.id, updatedBlog)
    console.log(response)

  }

  return (
    <>
  {buttonText === "view" ?   
  <div style={blogStyle}>
    {blog.title} {blog.author} <button onClick={() => setChecker(!checker)}>{buttonText}</button>
  </div>
  : <div style={blogStyle}>
      {blog.title} {blog.author} <button onClick={() => setChecker(!checker)}>{buttonText}</button>
      <p>{blog.url}</p>
      likes {blogLikes} <button onClick={handleLike}>like</button>
      <p>{blog.user?.username}</p>
    </div>}
  </>
  )
}
export default Blog

Here is my backend code that deals with the put request of the "new" like:这是我处理“新”请求的后端代码,例如:

blogsRouter.put('/:id', async (request, response) => {
  const body = request.body
  const user = request.user
  console.log(body)

  const blog = {
    user: body.user.id,
    title: body.title,
    author: body.author,
    url: body.url,
    likes: body.likes
  }

  const updatedBlog = await Blog.findByIdAndUpdate(ObjectId(request.params.id), blog, { new: true })
  response.json(updatedBlog)
})

Here is the specific axios handler for put request in another file within frontend directory:这是将请求放入前端目录中另一个文件的特定 axios 处理程序:

const update = async (id, newObject) => {
  const request = await axios.put(`${ baseUrl }/${id}`, newObject)
  return request
}

State updates are asynchronous in react, because of that when your API call happens:状态更新在反应中是异步的,因为当您的 API 调用发生时:

const handleLike = async (e) => {
    e.preventDefault()

    setBlogLikes(blogLikes + 1)
    
    const response = await blogService.update(blog?.id, updatedBlog)
    console.log(response)

  }

The updatedBlog object still contains old data, not the updated one. updatedBlog对象仍然包含旧数据,而不是更新后的数据。 So try the following, change your handleLike function to this:因此,请尝试以下操作,将您的handleLike函数更改为:

const handleLike = () => {
    setBlogLikes(blogLikes + 1)
}

And add your API call in the useEffect :并在useEffect中添加您的 API 调用:

useEffect(() => {
    setUpdatedBlog({
      user: blog.user?.id,
      likes: blogLikes,
      author: blog.author,
      title: blog.title,
      url: blog.url
    });
    blogService.update(blog?.id, {
      user: blog.user?.id,
      likes: blogLikes,
      author: blog.author,
      title: blog.title,
      url: blog.url
    }).then((response) => console.log(response));
  }, [blogLikes]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM