kinhs
kinhs

Reputation: 185

What is the best way to use req.query to target all posts associated with a user through ObjectId-mongoose and node

How best can I target all posts associated with a user using the user's objectId? I am using mongoose and node.js.

I currently have this code:

router.get("/", async(req, res) => {

const username = req.query.user;  // req.query is inbuilt. The last word .user is the keyword that will be used to query your logic
const catName = req.query.cat;

try {
   let posts;

   if(username) {
       posts = await Post.find({username: username})
   }
   else if(catName) {
        posts = await Post.find({categories:{
            $in:[catName]
        }})
   }
   else {
       posts = await Post.find()
   }

   res.status(200).json(posts)
} catch(err) {
    res.status(500).json(err)
}
})

It's not working for me. I want to get all the posts made by a user once you click on the user's name. username won't work for me because I used .populate() method from mongoose to ref username to my User Model from Post Model. So, username is now an objectId.

How do I query this using their objectId?

Upvotes: 0

Views: 98

Answers (1)

kinhs
kinhs

Reputation: 185

For anyone who may experience this challenge, especially those of us still learning. How I solved my problem: Since username is now a referenced objectId due to use of .populate() method, I was using the username in postman like this localhost:5000/api/posts?user/dave

'dave' is the username of the user. This didn't work because mongoose was waiting for the objectId to fetch the user. So, after hours of search, it came to my mind to use the objectId instead of the username and it worked. I was able to fetch only the posts made by that objectId. I had to do same thing in my React.js. My react route query looks like this:

<Link to={`/?user=${singleItem.username._id}`} className="link">

Everything is working fine, now.

Upvotes: 0

Related Questions