'Why returning more record when it should be one? Mongoose
I'm getting more records returned when it should be one only. Right now I have only 2 records on the MongoDB attendance schema
Here is my schema:
const attendanceSchema = mongoose.Schema({
WorkShopTitle: { type: String, trim: true }
enrollment: [{
studentUUID: { type: String, trim: true},
studentName: { type: String, trim: true },
}],
Status:{type: String, default:"Open", trim: true}
}, { timestamps: true });
When I run this query:
const checkStudentEnrolled = await Attendance.findOne({"$and":[{_id:{"$eq": '6210834ce3a7b51ad5bde65e'}},{"enrollment.studentUUID":{"$eq":'6506de7b0d32492c878307a1992f54e8'}}]})
console.log(checkStudentEnrolled)
It returns both records John Doe and Mary Jane instead of John Doe only:
{
_id: new ObjectId("6210834ce3a7b51ad5bde65e"),
WorkShopTitle: 'Wellness',
Status: 'Open',
enrollment: [
{
studentUUID: '6506de7b0d32492c878307a1992f54e8',
studentName: 'John Doe',
_id: new ObjectId("6210846ffab50e051294c833"),
},
{
studentUUID: 'f324e86498e64b6e858cf34b742c1899',
studentName: 'Mary Jane',
_id: new ObjectId("6210fe9022c55c1edeffe8c4"),
}
],
createdAt: 2022-02-19T05:42:36.946Z,
updatedAt: 2022-02-23T06:09:31.911Z,
__v: 0
}
How should I write the query to see only one return? Thanks
An update to this post:
I have found the solution and here is the final code:
const checkStudentEnrolled = await Attendance.findOne({"$and":[{_id:{"$eq": '6210834ce3a7b51ad5bde65e'}},{"enrollment.studentUUID":{"$eq":'6506de7b0d32492c878307a1992f54e8'}}]},{ 'enrollment.$': 1 })
But I'm not sure how does it work and hope someone here could explain this part in particular { 'enrollment.$': 1 }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
