I encountered an error stating 'Cannot do inclusion on field guides in exclusion projection', which occurred when trying to populate data using pre middleware in my schema:
const tourSchema = new mongoose.Schema({
...
guides: [
{
type: mongoose.Schema.ObjectId,
ref: 'User'
}
]
});
tourSchema.pre(/^find/, function(next) {
this.populate({ path: 'guides' });
next();
});
The error only occurs when accessing the getAllTour handlers; however, it does not show up when accessing a specified tour.
// The error occurs here
exports.getAllTours = catchAsync(async (req, res, next) => {
const features = new APIFeatures(Tour.find(), req.query)
.filter()
.sort()
.limitFields()
.paginate();
const tours = await features.query;
res.status(200).json({
status: 'success',
length: tours.length,
data: {
tours
}
});
});
// No error happens here
exports.getTour = catchAsync(async (req, res, next) => {
const tour = await Tour.findById(req.params.id);
if (!tour) {
return next(
new AppError('No tour found! please check the ID correctly', 404)
);
}
res.status(200).json({
status: 'success',
requestedAt: req.requestTime,
data: {
tour
}
});
});
You can also view my code at this link
Possible solutions for the errors I am facing