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