tikoku
@tikoku

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

データベースの文字列が、オブジェクトに変換されてしまう。

データベースの文字列が、オブジェクトに変換されてしまう。

現在、udemyのShinさんの動画でMERN=MongoDB×Express×React×Node.jsのフルスタック技術を使って、あなたが普段利用しているSNSアプリを1から構築していく講座です。フロントエンドからバックエンドまで駆使できる市場価値の高いエンジニアになろう!を元に勉強しながら、自分なりに変えてみたりして作っています。
プロフィールを作成する際、バックエンドのAPIの方でusernameを検索、その後そのユーザに合うポストを取ってきて、userが投稿したものだけが表示されるようなAPIを使いました。それらを使ってReactで動的に動かそうとした際、データベースで文字列として設定されているusernameがオブジェクトとしてフロント側で取得されてしまいます。
3時間ほど格闘しましたが、APIが悪いのか、フロント側のコードが悪いのかわからなくなってしまいました。
解決方法を教えて下さい。

バックエンドのAPI

router.get("/profile/:username", async (req, res) => {
  try {
    // usernameでユーザーを検索 
    const user = await User.findOne({ username: req.params.username });
    // ユーザーのidでポストを検索
    const posts = await Post.find({ userId: user._id });
    return res.status(200).json(posts);
  } catch (err) {
    res.status(500).json(err);
  }
});

React側

export default function Timeline(username) {

  const[posts,setPosts] = useState([]);
  console.log("Timeline received username:", username); 

  useEffect(() => {
    // 非同期関数を定義
    const Getposts = async () => {
      try {
        console.log("Username in Getposts:", username);
        const response = username 
      ? await axios.get(`/posts/profile/${username}`)
      : await axios.get("/api/posts/Pick-Up/67600e66bff8110fda22d3b3");
        setPosts(response.data)
      } catch (error) {
        console.error("Error fetching posts:", error);
      }
    };Getposts(); // 非同期関数を呼び出す
  }, []);
  


  return (
    <div className="timeline">
    <section className="section">
      <div className="nameofSection" id="PICKUP">
      <h1 className="section-headline">Pick Up</h1>  
      </div>
      </section>
        <div className="timelinewrapper">
        <Share/>
        {posts.map((post)=>(
          <Post post= {post} key={post._id}/>
        ))}
        </div>
    </div>
  )
}
 

試したこと

エンドポイントを変えてみたり、データベースを更新してみたり、mongodbのUserSchemaを触ってみたのですが何も変わらないどころか、internal 500 や 404エラーが出るなど悪化してしまいました。

0

1Answer

フロントエンド側で Timeline コンポーネントに username を渡している部分に問題がありそうです。どこかで <Timeline username={username}> していると思いますが、その周辺のコードを貼ってください。

0Like

Comments

  1. @tikoku

    Questioner

    回答ありがとございます、こちらがフロントの周辺コードです。

    import React,{useEffect,useState} from 'react'
    import "./MyProfile.css";
    import ArrowBackIcon from '@mui/icons-material/ArrowBack';
    import Timeline from '../timeline/Timeline';
    import axios from 'axios';
    
    
    
    export default function MyProfile() {
      const IMAGE_FOLDER = process.env.REACT_APP_IMAGE_FOLDER;
    
      const[user,setUser] = useState({});
    
      useEffect(() => {
          const Getuser = async () => {
            try {
              const response = await axios.get(`/api/users?username =LOL`);
              console.log(response);  
              setUser(response.data);
            } catch (error) {
              if (error.response) {
                console.error('Error response:', error.response);
              } else if (error.request) {
                console.error('Error request:', error.request);
              } else {
                console.error('Error message:', error.message);
              }
            }
          };
          Getuser();
        }, []);
      return (
        <div className="Profile">
          <div className="ProfileWrapper">
            <div className="profileTobbar">
              <div className="ArrowBack">
              <ArrowBackIcon/>
              </div>
              <span className="UserTopbarName">Profile</span>
            </div>
            <div className="profileSpace">
            <div className="ProfileBackgroundImg">
              <img src={IMAGE_FOLDER+"/Profile/nightViews.jpg"} alt="BackImage" className="profileCover"/>
              <img src={IMAGE_FOLDER+"/Profile/Mycutecat.JPG"} alt="Icon-image" className="ProfileIcon" />
            </div>
    
    
            <div className="profileInformation">
            <div className="EditPlace">
              <button className="Editbutton">Edit</button>
            </div>
              <h1 className="profileName">{user.username}</h1>
              <span className="profileIntroduce">{user.desc}</span>
            </div>
            </div>
            <div className="profilePost">
              <Timeline username="LOL"/>
            </div>
          </div>
        </div>
      )
    }
    
  2. 横から失礼します。
    const response = await axios.get(/api/users?username =LOL);
    のスペースが気になりました。
    const response = await axios.get(/api/users?username=LOL);
    に修正してみてください。

Your answer might help someone💌