MongoDB Realm: Query a Relationship

Viewed 103

here is my problem:

export const PostSchema = {
  name: "Post",
  primaryKey: "_id",
  properties: {
    _id: "string",
    comments: "Comment[]"
  },
};

export const CommentSchema = {
  name: "Comment",
  primaryKey: "_id",
  properties: {
    _id: "string",
    post: "Post"
  },
};

// Original Query:
const posts = realm.objects("Post");
console.log(posts);

// Original Query query results in:
[
      {
        _id: "post_1",
        comments: [],
      },
      {
        _id: "post_2",
        comments: [],
      },
      ...
];

// I'm looking for a query with the following result:
[
      {
        _id: "post_1",
        comments: [
          {
            _id: "Only the first (newest) comment post_1",
          },
        ],
      },
      {
        _id: "post_2",
        comments: [
          {
            _id: "Only the first (newest) comment post_2",
          },
        ],
      },
      ...
];

//My current solution therefor is:
let data = realm.objects("Post").map((post) => {
      return {
        ...post.toJSON(),
        comments: m.linkingObjects("Comment", "post").slice(0, 1),
      };
});

I'm not sure if this is the right/optimal solution.

If I understood correctly, then I make an extra request for the first comment for each post?

So if I have 20 posts, that's 20 extra requests? That would be very impractical?

Is there a better way?

I also tried Inverse Relationships.

But with this method I always get all the comments for a post which is a lot of unnecessary data?

THX for any help :-)

1 Answers
db.posts.aggregate([
  {
    $lookup: {
      from: "comments",
      localField: "comments",
      foreignField: "_id",
      as: "comments",
      pipeline: [
        { $sort: { _id: 1 } },
        { $limit: 1 }
      ]
    }
  }
])

mongoplayground

Related