Home > OS >  How to find two different data in single query - mongoose
How to find two different data in single query - mongoose

Time:12-25

I was trying to get my followers post and its working properly.

  let followingUsersPost = await Post.find({ user: { $in: currentUser.following } })
    .populate('user', '_id name username')
    .sort({ createdAt: -1 });

But Now i also want to search my own posts, in same query (to get all data and merge it together)

This is what i have tried, but its showing only my posts

  let followingUsersPost = await Post.find({ user: { $in: currentUser.following }, user: currentUser._id })
    .populate('user', '_id name username')
    .sort({ createdAt: -1 });

CodePudding user response:

The second user field in your query overwrites the first. You can just merge following and current users ids. For example:

  let followingUsersPost = await Post.find({ user: { $in: [...currentUser.following, currentUser._id] } })
    .populate('user', '_id name username')
    .sort({ createdAt: -1 });
  • Related