Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

I'm trying to create and fetch quizzes for a particular user using userId as parameters


I'm trying to create and fetch quizzes in router using NodeJs, but it keeps fetching me quizzes of every user and not only the user that is logged in

const prefix = "/:userId/quizzes";

router.get(`${prefix}/my-quizzes`, userAuth, async (req, res) => {
  try {
    const quizes = await Quiz.find().populate({
      path: "category",
      select: ["name"],
    });

    res.send(quizes);
  } catch (error) {
    return res.status(404).json({
      message: "Can't fetch quizes !",
      success: false,
    });
  }
});

Solution

  • You just need to add a query using the proper userId taken from the req.param, like so:

    await Quiz.find({userId: req.param.userId})