Search code examples
javascriptnode.jsmongodbmongoosemongoose-populate

Is it possible to query by populate document in Mongoose


I also tried in mongoose doc and MongoDB community but I couldn't find any solution.

How can i query document by populated document?


Solution

  • You should use an aggregation pipeline in order to achieve this. The following code will perform the lookup (same as populate) first and then match on the populated fields:

    const story = await Story.aggregate([
      {
        "$lookup": {
          "from": "authors",
          "localField": "author",
          "foreignField": "_id",
          "as": "author"
        }
      },
      {
        $match: {
          "author.name": "Ian Fleming"
        }
      }
    ])