0

I have 2 collections in my mongoDB database, "posts" and "likes". The schemas are like this (simplified):

// PostSchema
{
  _id: Number,
  user_id: Number,
  title: String,
  text: String,
  timestamp: Date,
  likes: Number
}

// LikeSchema
{
  _id: Number,
  user_id: Number,
  post_id: Number,
  timestamp: Date
}

When someone likes a post, I create a new document in the Likes collection, and I update the "likes"-value in the corresponding Post document. When someone dislikes, I delete the Like document and decrease the "likes"-value in the corresponding Post document.

I now want to query all posts, sorted on timestamp (descending), and I want to show if a post is liked by the user. So I want to fetch all post information + a boolean indicating a user has liked a post or not (a Like document exists for the user ID + post ID).

In SQL, I would do something like this with a subquery or a join, but I have no clue how to do this in mongoDB/mongoose. What is the best solution to do this for every post?

Sam Leurs
  • 1,592
  • 1
  • 19
  • 48
  • 1
    Does this answer your question? [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/questions/2350495/how-do-i-perform-the-sql-join-equivalent-in-mongodb) – Alex Blex Sep 29 '20 at 12:04
  • @AlexBlex: yes, ``$lookup`` is what I need. Thank you! – Sam Leurs Sep 29 '20 at 17:45

0 Answers0