0

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 Answers1

0

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

NullEe
  • 11
  • 2
  • I tried with ObjectId as well, but didn't worked – Ashwani Sharma Jan 18 '23 at 04:59
  • can you share some records? – NullEe Jan 18 '23 at 06:57
  • Student: `{ "_id" : ObjectId("63gd1dc708c35fd11431e87d"), "name" : "Joy", "subject" : ObjectId("63gd1dc808c35hfgr3455e67l"), "subjectTeacher" : "John", "__v" : 0 }` Subject: `{ "_id" : ObjectId("63gd1dc808c35hfgr3455e67l"), "subjectName" : "Maths", "__v" : 0 }` – Ashwani Sharma Jan 18 '23 at 10:36
  • to query that, first you should find your Maths Id and instead of searching by it name, you should search by the ID. or use embedded object. its good to check this one too : https://stackoverflow.com/questions/19572854/mongodb-query-on-populated-fields `const records = await this.studentModel.find({name: "Joy", subject: "63gd1dc808c35hfgr3455e67l"}); ` and this one must give you result. – NullEe Jan 18 '23 at 14:08
  • tried this also, but still not working – Ashwani Sharma Jan 18 '23 at 16:43