0

Documents must be filtered together with related collections. Using the SQL example (TypeORM/Postgres):

const temp = await queryRunner.manager.getRepository(ExperimentEntity).find({
            where: {
              id: entryId,
              user: {
                id: userId,
                firstName: 'John',
              },
            },
          });

Here I am specifying a nested WHERE condition that affects for two tables (experiment->user). How can I do something similar in Mongoose (using virtual, aggregate or something else)?

As a temporary solution, I wrote the following code, however, I would not want to send unnecessary documents from the database to the server in order to cut off some of them after. I would like this to happen at the database level.

const temp = await this.experimentModel
      .find(
        { title: 'test' },
      )
      .populate({ path: 'user' })
      .exec()
      .then((resultArr) => {
        return resultArr.map((el) => {
          if (el.user.firstName === 'John' && el.id === userId) {
            return el;
          }
        });
      });

user path from experimentModel:

@Prop({ required: true, type: mongoose.Schema.Types.ObjectId, ref: UserEntityM.name })
  user: UserDocument;

Also, I will clarify that match inside populate is not what I need. It will only filter inside populate but will not affect the overall array of documents returned.

hash0
  • 1
  • 2
  • [Related Answer](https://stackoverflow.com/questions/17535587/mongoose-query-a-populated-field) – Sathya Aug 24 '23 at 03:41

0 Answers0