How to query records in mongoose with schema having compound index with normal field and referenced field?

107 Views Asked by At

I have a Student Schema defined using mongoose. To create a primary key with both name and subject field, i have created a compound index with name and subject field.

@Schema()
export class Student {

  @Prop({ type: String, required: true, unique: false })
  name: string;

  @Prop({
    type: mongoose.Types.ObjectId,
    required: true,
    ref: 'subject',
    unique: false,
  })
  subject: mongoose.Types.ObjectId;

  @Prop({ type: String, required: true })
  subjectTeacher: string;

}

export const StudentSchema = SchemaFactory.createForClass(
  Student,
).index({ name: 1, subject: 1 }, { unique: true });

To query the record from the collection with both fields of a primary key, i am writing the below query but unable to fetch data, can somebody please help me with this?

const records  = await this.studentModel.find({name: "Joy", subject: "Maths"});

console.log(records);  // null
1

There are 1 best solutions below

5
On

type of subject defined as ObjectId, subject "Maths" is an object id?