Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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;

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the documentation for findById() it's stated that:

This function triggers the following middleware.

  • findOne()

findById() is also not mentioned in the list of query middleware.

So try this:

assignmentSchema.pre('findOne', function (next) { … })

Also, it's stated here that middleware should be declared before creating the model:

assignmentSchema.pre('findOne', function (next) { … })

const Assignment = mongoose.model('Assignment', assignmentSchema);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda