0

I am still fairly new to dynamic routing and although it makes sense, I am having issue implementing it correctly. Below is a function I want to grab the user's purchases from the database and export it as a csv. I had it working on local mongoDB but when I moved to Atlas for hosting, it only grabs the first person listed in the database and not the person logged in. Could I get some guidance on why my req.params is not working. Thank you in advance.

(This route would fall under app.use(/profile, profile) in the server)

 profile.js

// DOWNLOADING CSV OF PURCHASES
router.get("/purchased-items/:id", csvAbuseLimiter, (req, res) => {
  if (req.isAuthenticated()) {
    User.findOne({ id: req.query.id }, (err, foundUser) => {
      if (foundUser) {
        console.log(foundUser);
        const userPurchases = foundUser.purchases;
        const fields = ["name", "order", "duration", "asset"];
        const json2cvsParser = new Parser({ fields });
        try {
          const csv = json2cvsParser.parse(userPurchases);
          res.attachment(`${req.user.username}-purchases.csv`);
          res.status(200).send(csv);
          req.flash("success", "successful download");
        } catch (error) {
          console.log("error:", error.message);
          res.status(500).send(error.message);
        }
      }
    });
  }
});

person logged in Person logged in

What the route is pulling. Actual Response

kofi boateng
  • 95
  • 3
  • 9

1 Answers1

0

In the code provided you are using req.query.id and not req.params.id

Montgomery Watts
  • 3,806
  • 2
  • 10
  • 24
  • I have also tried req.params.id and it still does the same thing. I am currently retesting it as I type and it pulled the same query as posted above. Would I need to change the attribute from findOne? – kofi boateng Dec 24 '21 at 19:05
  • On closer inspection, your document does not have an `id` field. It has an `_id` field, which has the type `ObjectId`. This is a common pitfall for people getting started with Mongoose. – Montgomery Watts Dec 24 '21 at 19:09
  • That helps me understand why not to use id and I appreciate that! My last problem now is that after I turn the code async --> const query = await User.where({username:req.params.username}) its holding because the query is not picking up username from the req but if I use req.user.username it will pick up the query immediately. – kofi boateng Dec 24 '21 at 19:26
  • @kofiboateng That's dependent on how you are passing the data to the request handler. I suspect it's related to some middleware. – Montgomery Watts Dec 24 '21 at 19:43