mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Projection Select Not Working when i'm using mongoose-autopopulate #118

Closed DevNinja56 closed 5 months ago

DevNinja56 commented 5 months ago

Projection Select not working

this is my schema

export class Test extends Document { @Prop({ type: String, required: true }) title: string;

@Prop({ type: [MongooseSchema.Types.ObjectId], ref: 'Subject', required: true, autopopulate: { maxDepth: 2 }, }) subjects: string;

@Prop({ type: String, default: null }) description: string;

@Prop({ type: String, default: null }) overview: string;

@Prop({ type: String, default: null }) eligibility_criteria: string; }

export type TestDocument = HydratedDocument; export const TestSchema = SchemaFactory.createForClass(Test).plugin( require('mongoose-autopopulate'), );

@ApiBearerAuth() @Get(':id') @ApiOperation({ summary: 'Get single Test by ID' }) async findOne(@Res() response: Response, @Param('id') id: string) { try { const data = await this.testService.findOne({ _id: id }, { title: 1, subjects: { name: 1, topics: 0 } },); if (!data) { throw new NotFoundException('Enter a valid Test ID'); }

  generalResponse({
    response,
    message: 'Test found successfully',
    status: HttpStatus.OK,
    data,
  });
} catch (error) {
  throw new HttpException(error['message'], error['status']);
}

}

retrive an error message

"message": "Cannot do exclusion on field topics in inclusion projection",

DevNinja56 commented 5 months ago

"message": "Cannot do exclusion on field topics in inclusion projection",

vkarpov15 commented 5 months ago

This doesn't look like a mongoose-autopopulate issue, it's just that your projection is malformed. If you want to project in just title and subjects.name, use the following projection: { title: 1, 'subjects.name': 1 }, there's no need for topics: 0.