【问题标题】:Why won't my get route run my mongoose query?为什么我的 get route 不能运行我的 mongoose 查询?
【发布时间】:2021-01-25 17:14:12
【问题描述】:

我正在构建一个应用程序,用户可以在其中将博客文章发布到主页。现在,我只检索不是由登录用户发布的帖子。下面是前端的axios请求:

  //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();
  }

getToken() 函数成功获取正确的用户和相关 id。然后我将 id 传递给我的 getPosts 函数,该函数在后端向该路由发出 get 请求:

// 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);
  }
});
console.log('GET POSTS FROM OTHER USERS') 和 console.log(req.params) 都在我的终端中运行和打印,但是在查找用户和查找帖子时没有其他任何事情发生。当我在前端控制台记录响应时,我得到:

为什么我的回复中没有返回任何数据?我知道我正在走路线并且猫鼬查询写得正确。我缺少一些异步行为吗?

【问题讨论】:

    标签: reactjs express mongoose axios mongoose-schema


    【解决方案1】:
    const user = await User.find({ _id: req.params });
    

    req.params 是一个对象,您需要提取要传递给查询的 id。

    这是一个如何解构对象的示例。您可能需要调整分配以匹配属性名称。

    const { id } = req.params;
    

    【讨论】:

      猜你喜欢
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 2022-06-16
      • 2018-06-23
      相关资源
      最近更新 更多