Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda