mongoose-paginate-v2 icon indicating copy to clipboard operation
mongoose-paginate-v2 copied to clipboard

Query on populate field

Open necm1 opened this issue 2 years ago • 1 comments

Hi!

I tried multiple times to query my populate field to get entries of a specific user. Actually, I don't really know how to do this.

I tried to use the match object but it gives me null as the result including multiple entries not belonging to the user:

    const posts = await this.post.paginate(undefined, {
      limit: 10,
      page,
      populate: [
        {
          path: 'user',
          match: {_id: user.id},
          populate: {path: 'profile', model: 'Profile'},
        },
        {path: 'book'},
      ],
      sort: {_id: -1},
    });

That's the result I get (one entry of multiple entries which doesn't match the user id):

  {
    user: null,
    book: {
      created_at: 2021-12-16T05:31:45.802Z,
      image: null,
      authors: [Array],
      isbn: [Array],
      title: 'test book',
      id: '61bacf4112c14ff9d312523c'
    },
    type: 'post',
    content: 'test',
    created_at: 2021-12-02T11:11:19.000Z,
    updated_at: 2021-12-02T11:11:19.000Z,
    id: '625d7402eb84216a256d1df3'
  },

Is there any way to perform a WHERE-Condition in populate to get only entries of a specific user?

necm1 avatar Apr 20 '22 23:04 necm1

@necm1 You can try https://www.npmjs.com/package/mongoose-aggregate-paginate-v2 which might be good in your case.

aravindnc avatar Jun 08 '22 19:06 aravindnc