Home > database >  get count and merge with response in mongoose
get count and merge with response in mongoose

Time:12-20

I have some schemas like below.

var studentSchema = new Schema({
    name:{
        type: String,
        required: true
    },
});

var alertSchema = new Schema({
   student_id: {
        type: Schema.Types.ObjectId,
        ref: 'student',
        required: true
    },
    name:{
        type: String,
        required: true
    },
type:{
        type: String,
        required: true
    },
})

I need to get the count of alerts by student_id and merge it with student details. the result should be like below

[{
    "_id": "61b2e66ddecb23132cc9641c",            
    "name": "studentname1",
    "alertcount": 100,
},
{
    "_id": "61b2e66ddecb23132cc9641c",            
    "name": "studentname2",
    "alertcount": 50,
}]

thanks for advance

CodePudding user response:

You can use aggregation in mongoose.

First change your StudentSchema to include the alertCount :

var studentSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    alertCount : {type : Number , default : 0}
});

Then use aggregation on the alert model:

let alertCounts = Alert.aggregate([
   {$match : {name : student.name }}, // filters all the alerts where name is equal to a particular student's name from Student model
   {$count : "alertCount"}
])

This works for one student. You will have to apply this to every student in the dataset. You can use map function to achieve this.

Student.find({})
.then(students=>{
  students.map(student=>{
     let alertCounts = Alert.aggregate([
        {$match : {name : student.name }},
        {$count : "alertCount"}
     ])
     student.alertCount = alertCounts.alertCount;
     student.save()
  })
}

The code has not been tested and some minor changes might me required but I hope this gives an idea on how to achieve the functionality you want.

  • Related