i have two models relationship with mongoose. my first model looks like this:
const gradeSchema = new Schema(
{
grade_name: {
type: String,
required: true,
uppercase: true
},
major: {
type: Schema.Types.ObjectId,
ref: "Major"
},
active: {
type: Boolean,
default: true
}
},
{
timestamps: true
}
)
and my second models like this:
const majorSchema = new Schema(
{
major_name: {
type: String,
required: true,
},
major_type: {
type: String,
required: true,
minLength: 2,
unique: true,
uppercase: true
},
active: {
type: Boolean,
default: true
}
},
{
timestamps: true
}
)
i want to get all grades by major but i want majors to be filtered by active.
i try using populate.match but i got the majors response null:
const grade = await Grade.find()
.populate({
path: "major",
match: {
active: true
},
select: "-_id major_name major_type"
})
.where("active")
.equals(true)
.exec()
CodePudding user response:
You can make use of aggregation concept in mongo.
const data = await Grade.aggregate([
{
$match : {}
},
{
$lookup : {
"from" : "majors",
"pipeline" : [
{
$match : {
"active" : true
}
}
],
"as" : "majorInfo"
}
}
]).exec()