Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!