Search code examples
reactjsexpressmongooseaxiosmongoose-schema

Why won't my get route run my mongoose query?


I am building an app where users can make blog posts to the home page. Right now, I'm working on only retrieving posts that aren't by the logged in user. Here are the axios requests on the front-end:

  //Get user token
  getUser() {
    const token = this.props.location.state.token;
    if (token) {
      this.setState({ token: token });
      Axios.get('http://localhost:3000/api/posts', {
        headers: {
          'auth-token': token,
        },
      })
        .then((res) => {
          this.setState({ id: res.data._id });
          this.getPosts(res.data._id);
        })
        .catch((err) => {
          console.log(err);
          throw err;
        });
    }
  }

  //Get specific posts
  getPosts(id) {
    Axios.get(`http://localhost:3000/api/posts/all/${id}`)
      .then((res) => {
        console.log(res);
        this.setState({ posts: res.data });
      })
      .catch((err) => {
        console.log(err.message);
        throw err;
      });
  }

  componentDidMount() {
    this.getUser();
  }

The getToken() function successfully gets the correct user and relevant id. I then pass in the id to my getPosts function which makes a get request to this route on the backend:

// GET POSTS FROM OTHER USERS
router.get('/all/:id', async (req, res) => {
  try {
    console.log('GET POSTS FROM OTHER USERS');
    console.log(req.params);

    const user = await User.find({ _id: req.params });
    console.log(user);

    const posts = await Post.find({ email: { $ne: user[0].email } });
    console.log(posts);
    res.send(posts);
  } catch (err) {
    res.send(err);
  }
});
Both console.log('GET POSTS FROM OTHER USERS') and console.log(req.params) run and print in my terminal but nothing else happens with looking up the user and finding the posts. When I console log the response on the front-end, I get this: enter image description here

Why am I not getting back any data in my response? I know that I am hitting the route and the mongoose queries are written correctly. Is there some asynchronous behavior I am missing?


Solution

  • const user = await User.find({ _id: req.params });
    

    req.params is an object and you'll need to extract the id you want to pass to your query.

    Here's an example of how to destructure your object. You may need to adjust the assignment to match the property name.

    const { id } = req.params;