【问题标题】:Mongoose not fetching data until I refresh the database connection在我刷新数据库连接之前,Mongoose 不会获取数据
【发布时间】:2020-07-11 05:31:35
【问题描述】:

每当用户重新加载页面时,我都会尝试使用 mongoose 从 MongoDB 重新获取数据。但是,旧数据保留在那里,并且在我重新启动服务器之前不会获取新数据。

这是路由器:

router.post("/dashboard", (req, res) => {
  const userId = req.body.userId;
  User.findOne({ _id: userId }, (err, users) => {
    if (err) {
      console.log(err);
      res.status(500).send();
    } else {
      router.get("/dashboard", (req, res, next) => {
        const leagues = [users.leagues.premium, users.leagues.free];
        if (err) return next(err);
        res.status(200).send(leagues);
      });
    }
  });
}); 

这里是动作(Redux):

export const fetchLeagues = userId => dispatch => {
  axios.post("/api/leagues/dashboard", userId).then(
    setTimeout(function() {
      axios.get("/api/leagues/dashboard").then(leagues => {
        dispatch({
          type: GET_LEAGUES,
          payload: leagues
        });
      });
    }, 50)
  );
};

必须从特定用户获取数据,这就是为什么我要发布用户 ID,然后取回数据。不确定这是否是最好的方法。

澄清一下,我正在使用带有 redux 和 axios 的 MERN 堆栈来执行此操作。我尝试使用这个:MongoDB does not refresh data automatically?,但是当再次调用路由器时,我仍然无法让这个东西刷新/重新获取数据。谢谢。

【问题讨论】:

    标签: mongodb mongoose redux axios


    【解决方案1】:

    在这里执行 POST 请求然后 GET 请求似乎没有必要,因为您可以在单个请求中返回数据。

    数据被持久化的原因是,当您声明 router.get('/dashboard') 路由时,您会永久对该路由进行硬编码以获取第一个请求中的值。

    最好使用GET 请求,因为这正是您想要做的。

    例如

    router.get("/dashboard/:userId", (req, res) => {
      const userId = req.params.userId;
      User.findOne({ _id: userId }, (err, users) => {
        if (err) {
          console.log(err);
          res.status(500).send();
        } else {
          const leagues = [users.leagues.premium, users.leagues.free];
          if (err) return next(err);
          res.status(200).send(leagues);
        }
      });
    }); 
    
    // Where userId is now a string
    export const fetchLeagues = userId => dispatch => {
      axios.get(`/api/leagues/dashboard/${userId}`).then(leagues => {
        dispatch({
          type: GET_LEAGUES,
          payload: leagues
        });
      });
    };
    

    【讨论】:

    • 谢谢!!!虽然我收到了 404 错误,但在我更改了 2 件事后它对我有用!我改变了两件事:从 axios.post(/api/leagues/dashboard/${userId}) 到 axios.post(/api/leagues/dashboard/${userId.userId}) 和从 router.get() 到 router.post() 再次感谢您!
    • 我刚刚意识到第一个错误是因为我将 userId 作为对象返回,所以这不在你身上。对不起
    • 很高兴你能成功!我将答案更改为使用axios.get 而不是axios.post,因为据我所知,没有理由使用发布请求,但两者都可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多