Reputation: 223
I have two collections like checklists and tasks. Two schemas will look like below
checklist schema will look like beow
{
"_id": "5b7d0f77e231b6b530b0ee5a",
"audit_checklist_type": "Weekly"
}, {
"_id": "5b7d3f33e7a57f38084efb09",
"audit_checklist_type": "Daily"
}
Tasks Schema will look like below
{
"_id": "5b7d65daf74be318e8378cf9",
"checklist_id": "5b7d3f33e7a57f38084efb09"
}, {
"_id": "5b7d662df74be318e8378cfb",
"checklist_id": "5b7d3f33e7a57f38084efb09"
}
my query is
AuditChecklist.aggregate([
{
$match: {
$and: [
audit_checklist_type: "Daily"
]
},
},
{
$lookup: {
from: 'AuditTask',
localField: '_id',
foreignField: 'checklist_id',
as: 'TaskData',
},
},
]).exec()
I'm trying to get the output like
{
"_id": "5b7d3f33e7a57f38084efb09",
"TaskData ": [{
"_id": "5b7d65daf74be318e8378cf9",
"checklist_id": "5b7d3f33e7a57f38084efb09"
},
{
"_id": "5b7d662df74be318e8378cfb",
"checklist_id": "5b7d3f33e7a57f38084efb09"
}
]
}
But for me resulting TaskData output is empty. Any help is greatly appreciated. Thanks in advance!
Upvotes: 5
Views: 23320
Reputation: 46491
Mongooose pluralise the database name So instead of using AuditTask
you should use audittasks
OR
You can first import the database in your file like:
// ESM:
import AuditTask from './AuditTask'
// or CommonJS:
const AuditTask = require('./AuditTask')
and use it in your $lookup
aggregation:
{ '$lookup': {
'from': AuditTask.collection.name,
'localField': '_id',
'foreignField': 'checklist_id',
'as': 'TaskData'
}}
Upvotes: 13