I am using Mongoose aggregation pipelines with the $lookup stage to populate referenced documents. How can I exclude specific fields from the populated documents while retaining all other fields in the original document?
Example:
There is a Task schema that contains the ‘case’ field referenced from the Case schema. I want that, while querying the tasks using aggregation and lookup, I want to exclude some fields of the Case schema but include all fields of the Task schema.
(Include all field of Tasks, and only case_id, case_number from case (exclude rest all from case))
Task Schema
const mongoose = require('mongoose');
const taskSchema = mongoose.Schema({
case: {
type: mongoose.Schema.Types.ObjectId,
ref: "Case"
},
task_field_2: {
type: String
},
task_field_3: {
type: String
},
.
.
.
task_field_N: {
type: String
}
})
module.exports = mongoose.model('Task', taskSchema);
Case Schema:
const mongoose = require("mongoose");
const caseSchema = new mongoose.Schema({
case_id: {
type: Number,
unique: true,
},
case_number: {
type: String,
},
case_field_2: {
type: String
},
case_field_3: {
type: String
},
.
.
.
case_field_N: {
type: String
}
})
module.exports = mongoose.model('Case', caseSchema);
I tried to do this, but it is excluding all fields of Tasks also.
$project: {
"case.case_id": 1,
"case.case_number": 1,
},