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

116
Visualizações
Write .aggregate query inside a different schema.methods mongoose

I am trying to run an aggregation query of the first model in the schema.methods of the second schema, which is being called in the post save of the first Model.

Sample code:

// First Model
const FirstSchema = new mongoose.Schema({
// Some fields
})
FirstSchema.post('save',async function (){
const first = SecondModel.findOne({_id:mongoose.Types.ObjectId('stringId')}) 
first.getResults()
})

const FirstModel= mongoose.model("FirstModel", FirstSchema );

module.exports = FirstModel;

// Second Model
const SecondSchema = new mongoose.Schema({
// Some fields
})
SecondSchema.methods={
getResults: async function(){
const test1 = await mongoose.model("FirstModel").find()
const test2 = await mongoose.model("FirstModel").aggregate(someAggregationpipeline)
console.log(test1)
console.log(test2)
}
}
const SecondModel= mongoose.model("SecondModel", SecondSchema);

I get an empty array for test2 while I get the correct result for the test1.

Also, I am getting the correct output when I run the same aggregation pipeline in MongoDB Compass Aggregations

about 4 years ago · Juan Pablo Isaza
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