预挂钩不适用于查找查询
The pre hook is not working with find queries
/*The pre hook is supposed to populate the teacher field, but for some reason it didn't.Somehow when populate directly from the controller it works!*/
exports.getAssignment = catchAsync(async (req, res) => {
const assignment = await Assignment.findById(req.params.id).populate(
'teacher'
);
if (!assignment) {
return next(new AppError('No assignment found with this ID', 404));
}
res.status(200).json({
status: 'success',
assignment,
});
});
/*But when I use with the pre hook it doesn't get excuted! */
const mongoose = require('mongoose');
const assignmentSchema = new mongoose.Schema(
{
teacher: { type: mongoose.Schema.ObjectId, ref: 'User' },
group: { type: mongoose.Schema.ObjectId, ref: 'Group' },
AssignedAt: { type: Date, default: Date.now() },
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
const Assignment = mongoose.model('Assignment', assignmentSchema);
assignmentSchema.pre('findById', function (next) {
console.log('is this running');
this.populate({
path: 'teacher',
select: 'firstName',
});
next();
});
module.exports = Assignment;
在 findById()
的文档中指出:
This function triggers the following middleware.
findOne()
findById()
也没有提到in the list of query middleware.
所以试试这个:
assignmentSchema.pre('findOne', function (next) { … })
另外,here 中间件应该在创建模型之前声明:
assignmentSchema.pre('findOne', function (next) { … })
const Assignment = mongoose.model('Assignment', assignmentSchema);
/*The pre hook is supposed to populate the teacher field, but for some reason it didn't.Somehow when populate directly from the controller it works!*/
exports.getAssignment = catchAsync(async (req, res) => {
const assignment = await Assignment.findById(req.params.id).populate(
'teacher'
);
if (!assignment) {
return next(new AppError('No assignment found with this ID', 404));
}
res.status(200).json({
status: 'success',
assignment,
});
});
/*But when I use with the pre hook it doesn't get excuted! */
const mongoose = require('mongoose');
const assignmentSchema = new mongoose.Schema(
{
teacher: { type: mongoose.Schema.ObjectId, ref: 'User' },
group: { type: mongoose.Schema.ObjectId, ref: 'Group' },
AssignedAt: { type: Date, default: Date.now() },
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
const Assignment = mongoose.model('Assignment', assignmentSchema);
assignmentSchema.pre('findById', function (next) {
console.log('is this running');
this.populate({
path: 'teacher',
select: 'firstName',
});
next();
});
module.exports = Assignment;
在 findById()
的文档中指出:
This function triggers the following middleware.
findOne()
findById()
也没有提到in the list of query middleware.
所以试试这个:
assignmentSchema.pre('findOne', function (next) { … })
另外,here 中间件应该在创建模型之前声明:
assignmentSchema.pre('findOne', function (next) { … })
const Assignment = mongoose.model('Assignment', assignmentSchema);