I want to find all task by first_name of claimant.
Task Schema:
const TaskSchema = mongoose.Schema({
case: {
type: mongoose.Schema.Types.ObjectId,
ref: "Case"
},
});
Case Schema:
const CaseSchema = new mongoose.Schema({
claimant: {
type: mongoose.Schema.Types.ObjectId,
ref: "Claimant"
},
});
Claimant Schema:
const ClaimantSchema = new mongoose.Schema({
first_name: {
type: String,
required: true,
},
last_name: {
type: String,
required: true,
}
});
I tried this but it give empty array:
const searchTasks = await Task.find({ "case.claimant.first_name": "demoName" });
How to do this ?
2
Answers
You can’t directly access nested properties, but you can populate the related data. My playground, you can put all in one file:
index.js
playground.js
models:
data:
query:
filter:
output:
console.log(searchTasks)
console.log(searchTasks[0].case)
please inform me about your result.
The most straightforward way you can achieve the desired results is to use aggregate. The mongoose populate method does not allow you to filter the parent documents based on a conditional match on one of the child documents:
See the docs for a full explanation. Here is the
aggregate
solution: